you can use git without github , use git to push storage on server.
git has GUI (desktop).
why you must learn git?
developers contribute to the same project.
you can revert changes.
you can collaborate to fix issues.
you can collaborate to create new features.
you can solve conflict.
you can organize feature (commits).
Before using GIT we need to understand some Definitions :
Repository is a storage that keep date organized and a community can access this data.
Master is a main of data .
Branch This is usually used with teams so that there is no conflict in the data (each member in team have own branch and in the end combination them in the master) .
init when you start your first time with git you can add your username with git and email that will be used with push .
Add to add files that are ready to be commited .
Commit (snapshot or checkpoint) is to submit all changes that you do to your added files to be ready to be pushed to your server move it in local repositiory .
Status to check what the file added and not commited.
Remote to connect the local repo and the repo on server .
Push upload local changes to remote.
pull you pull changes from remote repo to your local.
pull request tell other about changes to pull it from local to remote .
Clone copy of the repositiory origin to your local Device .
Fetch copy a branch and save it as a new branch to your device .
Git branch get all branches in your repository.
git branch Name create a new branch with a Name.
Checkout is to move between branches.
this is all stages
git add * (to move data from working dir to staging area).
git commit -m "commit name" (to move from staging area to local repo).
git push RemoteName BranchName . (move from local repo to remote repo), we use command line (git remote -v) to get RemoteName.
git pull origin.
Important Notes:
create repo for every project.
create a new branch for every feature or enhancement .
no need to connect to remote when working.
anyone can push and pull depend on permissions.
Note: There are two ways to communicate with your repository with HTTP or SSH I find that ssh is the famous one so I decided to use it . As there are communication that going to happen between two devices so we need to set up the communication between them and make it authorized .So we need to generate a RSA code that the protocol that ssh use for Communicating
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Enter a file in which to save the key (/home/you/.ssh/id_rsa): [Press enter]
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]
so to add the code to our ssh protocol on our Ubuntu
ssh-add ~/.ssh/id_rsa
to Get a copy from the RSA code to add to my gitlab server side We need to install
sudo apt-get install xclip
to take a copy to your clipboard
xclip -sel clip < ~/.ssh/id_rsa.pub
Commands Usually Used in Git
1. Git clone
Git clone makes an identical copy of the latest version of a project in a repository and saves it to your computer.
<command line in git> git clone <https://name-of-the-repository-link>
2. Git branch
By using branches, several developers are able to work in parallel on the same project simultaneously.
<command line in git> git branch <branch-name>
This command will create a branch locally. To push the new branch into the remote repository, you need to use the following command:
git push -u <remote> <branch-name>
a-Viewing branches: <command> git branch
b-Deleting a branch: <command> git branch -d <branch-name>
3. Git checkout
To work in a branch, first you need to switch to it. We use git checkout mostly for switching from one branch to another.
<command line in git> git checkout <name-of-your-branch>
4. Git status
The Git status command gives us all the necessary information about the current branch.
<command line in git> git status
5. Git add
We need to use the git add command to include the changes of a file(s) into our next commit.
<command line in git> git add .
6. Git commit
Git commit is like setting a checkpoint in the development process which you can go back to later if needed.(Move files from stage to repo in a local )
<command line in git> git commit -m "commit message"
7. Git push
After committing your changes, the next thing you want to do is send your changes to the remote server. Git push uploads your commits to the remote repository.
<command line in git> git push <remote> <branch-name>
8. Git pull
The git pull command is used to get updates from the remote repo.
git pull
9. Git merge
The git pull command is used to get updates from the remote repo.
git pull
First you should switch to the dev branch:
<command line in git> git checkout dev
Before merging, you should update your local dev branch:
<command line in git> git fetch
Finally, you can merge your feature branch into dev:
git merge <branch-name>
IMPORTANT NOTE: the trailing . in the previous line is important!
git commit -m "Restoring old source code"
How to Compare files ?
Using <command line in git> (git diff ) without any arguments: will compare each modified files in your file system against the files in the current checked-out branch (or) tag.
Using <command line in git> (git diff <tag(or)branch name>): will compare each modified files in your file system against the files in the specified branch (or) tag without using checked-out branch (or) tag.
Using <command line in git> (git diff <path/to/file_name (or) path/to/folder>): will compare the specified file or files in the folder in your file system against the current checked-out branch (or) tag.
Using <command line in git> (git diff <tag1(or)branch1 name> <tag2(or)branch2 name>: will compare all modified files between two branches / tags.
1. //pull the latest changes of current development branch if any
<command line in git> git pull (current development branch)
2. //switch to master branch
<command line in git> git checkout master
3. //pull all the changes if any
<command line in git> git pull
4. //Now merge development into master
<command line in git> git merge development
5. //push the master branch
<command line in git> git push origin master
What is the Normal Process to start working on a new Feature ?
create a new branch
git branch
steps
checkout master. git checkout master
update master. git pull --rebase origin
create branch. git branch branch-name
coding. code.....
commit. git commit -m "commit name"
checkout master. git checkout master
update master. git pull --rebase origin
checkout local branch. git checkout branchName
merge. git merge
push. git push
pull requests
Pull requests let you tell others about changes you've pushed to a branch in a repository on GitHub. Once a pull request is opened, you can discuss and review the potential changes with collaborators and add follow-up commits before your changes are merged into the base branch.
Steps
fork the repo who do you want to edit.
add changes.
create a new pull request.
wait untill the collaborators confirm and merged this changed.
GitHub Actions
Automate, customize, and execute your software development workflows right in your repository with GitHub Actions. You can discover, create, and share actions to perform any job you'd like, and combine actions in a completely customized workflow.
![image](https://user-images.githubusercontent.com/61950354/1# GitHub Actions
Automate, customize, and execute your software development workflows right in your repository with GitHub Actions. You can discover, create, and share actions to perform any job you'd like, and combine actions in a completely customized workflow.
Enter file in which to save the key (/c/Users/karem/.ssh/id_rsa): [Press Enter]
Enter passphrase (empty for no passphrase): [Press Enter]
Enter same passphrase again: [Press Enter]
Then Run and Copy SSH and Go to your Account and add it.
cat .ssh/id_rsa.pub
eval $(ssh-agent -s)
ssh-add ~/.ssh/id_rsa
Testing
What is testing ?
the execution of software and trying all its functions and properties in different ways and to examine all the possibilities that user may carry out while executing the software.
What are objectives we do testing?
It satisfies specified requirements:
study the software functionality in detail to find where the bugs are likely to occur.
finding defects:
ensure that each line of code it tested.
Preventing defects :
finding bugs as early as possible.
Testers must make sure that 100% of software work find and error: There will always be a missing bugs.
A tester effectiveness is reflected in the number of bugs found before the software is released to user: No connection >between user happiness and buts testers fount in software, the main concern for theme is only a working software.
Developing vs. Testing
We have a Bug but what is the Bug?
Is The deviation of the actual result from the expected result.`
A person makes an Error
That produce a Fault or a Bug in the program code.
that might causes a failure in the software.
Software Requirement Specification
Is detailed description (purpose, overall description, system feature, interface requirements) the main reference for Expected result
If there is no SRS:
Standards.
Communication.
Statistics.
Life Experience
In software testing there is not only a Software Bugs but there is also aSpecification Bugs .
Test Inputs
Valid inputs: happy scenarios.
Invalid inputs: bad scenarios.
Bug Addressing
What is it? Bug reporting >> Fixing bug >>Recheck it is bug free and there is no bug introduced.
How? on Bug Tracking System.
Test Suite: is Test cases of the same module by Test Procedure which is Test Execution all Test Steps
if:
pass AR==ER
fail AR!=ER
block no possibility to test
Test Case Documentation:
Unique id.
Bugs Priority: from P1 to P4.
Description.
Additional info.
Revision History.
Test procedure.
ER :expected result.
Revision History :Created (date/name) Modified(date/name)
maintainability of test case :
we need the simplicity and easy of changing a test case.
Do not include steps for obvious easy to guess scenarios.
Take repeat scenarios put those into an external document put a reference of this external document in test cases.
Do not build steps on an information in may be changed or deleted.
Avoid those test case practices:
Dependency between test cases.
poor description of test case.
4 levels of Testing - comparison
1. Unit Testing. component, module or unit testing.
To ensure that every unit is doing its function as it in specifications.
what? Is smallest component of the software (function, SQl query...).
who? Developer.
why?
Faster Debugging.
Easier to fix bugs and picked up earner.
Encouraging more refactoring.
Reducing future cost.
2. Integration Testing.
what? Testing modules together and evaluate interaction between them.
who? Tester by Stubs and driver dummy code for unfinished functions.
why?
Unit tests only test unit in isolation.
COTS or off-the-shelf are used can not be unit tested.
time consuming in system testing.
_Failures that will be discover after the system is very expensive.
Types
Big Bang Testing . _we will avoid using it completely.
4. Acceptance Testing. _ achieve the business needs of End User
What?
Alpha Test: Clint tries the software in software development environment
Beta Test: in his real environment.
Scaffolding
Driver>>Tested Unit>>stub.
Driver: used in Bottom UP Testing to test low level functions or modules.
Stub: used in Top Down Testing .
steps:
write.
compile.
test.
Reasons for Test Cases
Happy scenarioTest To pass.
Bad scenarioTest To fail.
Test Design Techniques
why?
To design the suitable test cases for each type and part of software, Write the right number of test cases to cover all code possibilities and write minimum number effective number of test cases .
types:
Black Box Testing Techniques. == 'Specification based testing'
Applies foe functional and non-functional testing, without reference to the internal structure of the system.
with:
mainly applicable to higher levels of testing (System Testing and Acceptance Testing).
types:
1. Equivalence Partitioning(EP)
when Range of data , not used separately but with BVA
Minimum number effective of test cases:
TC1= Valid Partition inside the range of data .
TC2= Invalid Partition outside the range of data .
2. Boundary value analysis (BVA)
when software that has a rage of data, only for numeric fields and date
Finding the boundary(upper and lower).
Test one value above and below.
=6 Test cases.
3. Decision Table
when many conditions and rules control the output.
4. State Transition.
when Transition between two states of a component or system(Screen dialogues, web site transitions, Embedded system ).
5. Use case technique.
Method of describing the software requirements.
parts:
Actors users of system.
Pre-conditions what are starting requirements for the use case.
Post-conditions the state the system will end up in once completed.
White Box Testing Techniques. =='Glass box Testing or Structure base Testing'
Testing based on an analysis of the internal structure of the component or system.
with:
mainly applicable to lower levels of testing (Unit Testing or integration testing).
1. Statement Testing
Aims to execute all statement at least once with the minimum number of test case.
2. Desertion Testing
Amin is to demonstrate that all decision have been run at least once.
When the code contains :i.e.(If/then/else/while)
Coverage measurement = the number of decision executed / the total number of decision.
Statement test cases for a segment of code will always =< of Branch / Decision test cases.
Branch/decision testing is a more complete form of testing than statement testing.
Exhaustive testing is impossible(risk analysis and priorities).
res
Fundamental Test Process
Test planning and control
Test Planning: Specification of test objectives(i.e. find defects as much as we can, Give information to decision making, ...)._
Control: (Ongoing activity )keep monitoring all the test activities as long as you work on project.
Comparing the plan with actual progress, if not Reporting then taking action.
Test analysis and design
Test analysis: Test basis(Requirements, Software integrity level, Risk analysis reports ,Structure of software, interface specification) the Test condition
Design: Test cases then prioritizing, identifying test data, prioritizing, test environment setup.
output: traceability matrix
Test implementation and execution
Implementation: create Test suites and implementing test pressures and create Test Data and Test harnesses(stubs and drivers). verify test environment setup
Execution Logging or recording Test Log file : (compare if Discrepancies AR != ER, tester name ,date ,AR, ER,TR), then retesting then the Regression testing
Evaluating exit criteria and reporting
Exit criteria: to determine when to stop(i.e. Test execution coverage ,fault found, cost or time).
Reporting: write test summary report for all stakeholders to know the stage we have reached.
Test closure activities
at each milestone(i.e. SW is released, Test project is completed or canceled, )
check: planned deliverables.
close: reports.
Document: system acceptance..
Finalizing Archiving: Handover Test ware(i.e. Test harness, tools ,test cases, procedures, test suites, data) to Maintenance organization_
3. Structure testing (white Box)with all Testing levels specially unit testing and integrated testing
code coverage : what is the number you have covered of code (statement coverage, decision coverage)
4. Testing Related to Change
types:
Confirmation testing(retesting) : After fix bugs.
Regression Testing
5. Maintenance-Testing
with all testing types and testing level
why
Modification
Migration
Retirement
then we need to do regression testing.
Impact Analysis
determine the the extent of effect on system and how much regression testing to do.
Static Techniques
Review: identify the mistakes in files manually without execution
Static analysis: Quality of code and error-free Automatically
Dynamic Testing
code execution
high coast and long time
Main objectives
Interface usability
Design efficiency
cod maturity
SRSD
SD, Use cases, UML diagram
SW Testing life cycle STLC
Requirement Analysis.
meeting with (Business Analyst, Architecture, Client, Technical Manager, Any Stakeholders)
choose the Testing Types (Functional ,security, performance)
Testing focus with my priorates
Test Planning.
Test plan Document.
Objective &scope of the project.
Testing types.
Testing effort estimation and resource planning.
Selection of testing tool if required.
Test schedules.
Roles and responsibilities.
Test deliverable.
Entry & Exit criteria.
Risks.
In scope &out of scope.
Test Case Development.
Create test cases for each module/function.
Preparing test data.
Requirements traceability matrix documentation if changed we do impact analysis.
Environment setup.
Test Execution.
Smoke Testing(validation Testing)
Start Test execution according to the test plan.
Define the status of each test case according to SRS(passed or failed or not applicable).
Report a bug through (Bug or Defect Tracking Tool like Jira, Mantis)
Status Report and send the report to developer.(Count of the founded bugs, Bugs Priorities, Bug Severity)
Start executing with new build
( Fixed bugs to close it, New functionalities.)
Confirmation Test
change the status to "closed as fixed, close as not a bug" .
Test the new features.
Make a regression testing.
Test Cycle Closure.
make acceptance testing and deliver UAT( user acceptance Testing) Document
write project Bugs report contains all the bugs found in this project(Fixed Bugs/Known issues).
Test case writing
Test case definition : _IEEE: Documentation of specified inputs or predicted result,
A group of activates which have expected results and actual results happen in a certain sequence in order to check the specification and advantage of the product.
The sources of Test Cases:
SRS document (use cases, user story ).
_Detailed description of a software system to be developed with its functional and non functional requirements.
Functional requirement.
non-fictional requirement.
may include Use cases. _
should have a review test
Graph.
Template sheet.
Email
Test Case Format
Test case attributes :
Test case ID. Unique identifier
Naming Convention
TC+ Project Name+ Function name +TC number
Test case Title/Description. short description of test case & should be effective to convey the test case
Test case Summary. Detailed description of test case & additional information needed for the test case to execute.
Pre-condition/Assumption. any pre-requisite required to excite the test case.
Any user data dependency
Dependencies on test environment
special setup
dependencies on any anther test cases
Test Steps Actual step to be followed or executed.
Start with an order.
Each step must have an expected result.
All steps must be in the same sequence.
Test Data. data that us used.
Excepted Result.
Actual result.
Test case states. pass/fail/not applicable.
Comments.
Test case Priority -(Critical/high/medium/low).
Bug reports
Bug ID: (problem , module Environment)
Bug Title.
Steps.
Expected Result.
Actual Result.
Severity. write the importance of the bug for the user depending on SRS (Showstopper/critical/height/medium/low)
priority ()
Attachment(Screen shot/Recorded Video)
Bug life cycle
Tester finds bug.
Developer analyze the bug(fixed/not a bug/need information/non reproducible)
Bug Statuses
Fixed.
Deferred.
need information.
not producible
Duplicate
not a bug
known issue
Experience-based techniques
informal
Error Guessing. write fault attack
Exploratory Testing. no or poor specification
_ write Test charter(Test objectives-time-boxes)
This picture is show a list of Testing Technique :
64 bit OS architecture capable of running 32-bit type applications
Installing Java for Android Studio:
Before you install the Android Studio IDE, you need to make sure your Ubuntu installation is armed and ready with the recommended Java development kit for Android Studio – Oracle JDK.
To check the version of Java
$ java --version
If you don’t have Java installed, the output should be something like:
Note: Make sure that you have updated the Advanced Package Tool (APT) before you move forward to install OpenJDK.
Install OpenJDK on Ubuntu
$ sudo apt install openjdk-14-jdk
All you have to do now is to set the “JAVA_HOME” and “PATH” environment variables and then you are done.
Save the bash file, restart the terminal, and type echo $JAVA_HOME to make sure the path is properly set.
Installing Android Studio From The Ubuntu Software Center
Locate the Ubuntu Software Center icon in your taskbar and use the search functionality to find Android Studio. Click install and let it download and run initial setup.
Install Flutter SDK on Ubuntu
System requirun the following command to begin signing licenses. rements
Operating Systems: Linux (64-bit)
Disk Space: 600 MB (does not include disk space for IDE/tools).
Install Flutter using snapd
$ sudo snap install flutter --classic
use the following command to display your Flutter SDK path:
$ flutter sdk-path
Run flutter doctor
$ flutter doctor
[-] Android toolchain - develop for Android devices
• Android SDK at /Users/obiwan/Library/Android/sdk
✗ Android SDK is missing command line tools; download from https://goo.gl/XxQghQ
• Try re-installing or updating your Android SDK,
visit https://docs.flutter.dev/setup/#android-setup for detailed instructions.
Install Android SDK Command-line Tools (latest)
On your Android Studio Project, click on the File and then “Settings“.
Check the box given for “Android SDK Command-line Tools (latest)” and then press the OK button
Agree to Android Licenses
Before you can use Flutter, you must agree to the licenses of the Android SDK platform. This step should be done after you have installed the tools listed above.
Make sure that you have a version of Java 8 installed and that your JAVA_HOME environment variable is set to the JDK’s folder. Android Studio versions 2.2 and higher come with a JDK,
run the following command to begin signing licenses.
Providers are the most important part of a Riverpod application. A provider is an object that encapsulates a piece of state and allows listening to that state.
Creating a provider
final myProvider = Provider((ref) =>MyValue());
in Riverpod we can have two providers expose a state of the same "type":
final cityProvider = Provider((ref) => 'London');
final countryProvider = Provider((ref) => 'England');
Provide data:
Provider
Future provider
Stream provider
State provider
Advantages
allows us to easily create, access, and combine providers with minimal standard code.
caching the data in memory
Install RiverPod
-add the latest version of flutter_riverpod as a dependency to our (pubspec.yaml) file.
-wrap our root widget in void main with a ProviderScope.
Steps to Create a provider
1- add Global provider
final nameprovider = Provider<String>( (ref)=>'name');
2- read the provider value inside the widget, we have two ways:
Using ConsumerWidget (rebuilding the whole page).
Using Consumer (rebuilding specific widget).
Note
to avoid caching data in memory we can use autoDispose
watch function interact with the reference of the provider.
let user = await Users.findOne({ email }).lean()
// if not exist return an error messge
if (!user) {
// status code is 404 not found
return res.status(404).json({ status: 'false', message: 'Invalid email or password' })
}
status code is 401 Unauthorized
const token = req.header('x-auth-token')
if (!token) {
// status code is 401 Unauthorized
res.status(401).send('access denied not auth......')
}
// if write invalide url or end point send to user an error message
app.all('*', (req, res, next) => {
res.status(404).json({
status: 'false',
message: 'Page not found !'
})
})
// listen on port 8080 local host
app.listen(8080, () => logger.info('server started 8080 ....'))
# Build User Schema
###### You can add or remove any attribute
- userName must be in lowercase to be unique and make all users name completely different
```sh
const UserSchema = new mongoose.Schema({
userName: { type: String,unique:true, required: true, lowercase:true,minlength: 3, maxlength: 44 },
email: { type: String, required: true, maxlength: 254 },
password: { type: String, required: true, minlength: 8, maxlength: 1024 },
phone: { type: Number, unique: true, minlength: 11, maxlength: 11 },
isAdmin: { type: Boolean }m
userEducation: {
university: { type: String, },
major: { type: String, },
faculty: { type: String, },
experince: { type: String, },
grade: { type: String, },
interest:
[{type:String}]
} ,
})
Schema validation using joi package
You can add or remove any attribute from your schema
```sh
//*validation on user inputs in login
function validateUserLogin(user) {
const JoiSchema = Joi.object({
email: Joi.string().email().min(3).max(25).required(),
password: Joi.string().min(8).max(512).required()
}).options({ abortEarly: false });
return JoiSchema.validate(user)
}
Build Registration
you can change any attributes independent on schema's attributes
// Take inputs from user for example
const { userName, email, password: plainTextPassword } = req.body
remove white spaces from userName
let userNameCheck =userName.replace(/\s+/g, '')
Use validate function
const validateError = validateUser(req.body)
// if validate error just send to user an error message
if (validateError.error) {
return res.json({ error: validateError.error.details[0].message })
}
check in database by any required attribute you want from schema for example by email
let user = await Users.findOne({ email }).lean()
if (user) {
return res.status(200).json({ status: 'false', message: 'email already in use' })
}
- You can change any required attribute form schema the change the message
```sh
let user = await Users.findOne({ userName }).lean()
if (user) {
return res.status(200).json({ status: 'false', message: 'userName already in use' })
}
If validate then
try {
// take from user userName , email and password and not care for any value else using lodash package
user = new Users(_.pick(req.body, ['userName', 'email', 'password']))
// encrypt the password using bcrypt package
// 10 is a vale of salt length to generate or salt to use (related by security)
user.password = await bcrypt.hash(plainTextPassword, 10)
// save userName without spaces
user.userName = userNameCheck
// generate token that have his id using jsonwebtoken package
const token = jwt.sign({ id: user.id }, 'privateKey')
// then save the user
await user.save()
// send his token in header and his data in body
return res.header('x-auth-token', token).json(_.pick(user, ['_id', 'userName', 'email']))
} catch (error) {
if (error.code === 11000) {
return res.json({ status: 'false', message: 'in use' })
}
throw error
}
Build Login
Take inputs from user for example
const { email, password: plainTextPassword } = req.body
you can change any attributes independent on schema's required attributes
Use validate function
const validateError = validateUser(req.body)
// if validate error just send to user an error message
if (validateError.error) {
return res.json({ error: validateError.error.details[0].message })
}
check in database by any required attribute you want from schema for example by email
let user = await Users.findOne({ email }).lean()
// if not exist return an error messge
if (!user) {
return res.status(200).json({ status: 'false', message: 'Invalid email or password' })
}
You can change any required attribute from schema then change the message.
let user = await Users.findOne({ userName }).lean()
// if not exist return an error messge
if (!user) {
return res.status(200).json({ status: 'false', message: 'Invalid userName or password' })
}
If validate then
try {
// compare between password and encrypted password of user using `bcrypt.compare`
const checkPassword = await bcrypt.compare(req.body.password, user.password)
// if password doesnt match return to user an error message
if (!checkPassword) {
return res.status(200).json({ status: 'error', error: 'Invalid email or password' })
}
// generate token that have his id and if admin or not using `jwt.sign`
const token = jwt.sign({ id: user._id, isAdmin: user.isAdmin }, 'privateKey')
return res.json({ status: 'ok', token: token })
} catch (error) {
// error code 11000 for duplicated attribute in database
if (error.code === 11000) {
return res.json({ status: 'false', message: 'in use' })
}
throw error
}
Build middleware
authentication middleware
check if user have token (auth)
module.exports =function (req, res, next) {
// get the token from header called x-auth-token
const token = req.header('x-auth-token')
if (!token) {
res.status(401).send('access denied not auth......')
}
try {
// decode the token to get the user info using `jwt.verify` from package jsonwebtoken
const decodeToken = jwt.verify(token, 'privateKey')
req.user = decodeToken
next()
} catch (er) {
res.status(400).send('wrong token ......')
}
}
change password inside the app for user that logged in
router.post('/', async (req, res) => {
// take the password from user and validate it
const { password: plainTextPassword } = req.body
// take the token from header
const token = req.header('x-auth-token')
// validate the password if not string
if (!plainTextPassword || typeof plainTextPassword !== 'string') {
return res.status(200).json({ status: 'false', message: 'Invalid password' })
}
// validate the password if less than 8 char
if (plainTextPassword.length < 8) {
return res.status(200).json({
status: 'false',
message: 'Password too small. Should be atleast 8 characters'
})
}
try {
// decode the token to get user data
const user = jwt.verify(token, 'privateKey')
console.log(user)
// get user id
const id = user.id
console.log(id)
// incrypt new password
const newPassword = await bcrypt.hash(plainTextPassword, 10)
// find the user by id and change the password
await User.updateOne(
{ _id: id },
{
$set: { password: newPassword }
}
)
res.status(200).json({ status: 'ok', message: 'password changed' })
} catch (error) {
res.json({ status: 'false', message: error.message })
}
})
Build Profile
middleware auth check first if user logged in and have a token
get('/', auth, async (req, res) => {
// find the user info by his id and not show the password at response using `select`
const profile = await User.findById(req.user.id).select('-password -__v')
res.json({ profile })
})
Build Course Schema
courses must have an author for each course so we need to get the author id to fetch his data with the course
to do this we need to take a reference from user schema
How can I add more validation to ensure for example :
1) the Username can't start with Sympols or Numbers
2) Username can't have spaces
3) Username can't be duplicated like email
Live while I am writing on Flutter GUI I validate if this username is used before In the database or not . To make it more clear I am writing first char "O" this less than 3 Paramters the FLutter Team will Raise flag that is less than 3 Char but after haveing for example "OOO" how we check instant without click on registration button and send that this username is booked from example .
4) In username is "OOO" is different from "ooo" is the validation function compare with taking in consideration the Capital of the Chars ?
Where is the documentation / Comments for this Code ?
After Have a some time in the backend code here is my Thoughts :
It is Very Important @omda07 and @mirette3 to have next Documentation :
1) What is the Structure of the Code
2) What is automatic Generated by tools and We didn't edit or Developed anything at and What we changed in some files and what we developed ?
3) I can see that in this path https://github.com/omarokasha1/TheFirstProject/tree/backend/loginAndRegister we have 5 Folders and 5 FIles what is the usage from each one ?
4) What is these status Numbers ? What are they referring to ? we need a table with the definition of each number .
5) We need a table of definition that will have a keyword like subscriber ?
6) Check Change Password Code , you need to make a lot of comments with some questions like :
what is this ? const JWT_SECRET = 'kdhakjdhwdhqwiu;hdl/akjd;lakhdulhdw$$@$#^324uoqdald'
7) I think we need to make a Journey for the backend to show that for example :
Starting from what is start with the server start without getting any inquiry from flutter or frontend
What happen in the code when we receive a inquiry for login how the code interact with the database
What happen in the code when we receive a inquiry for Registration how the code interact with the database
What happen when i request to change my password
all of these things need to be clear .
Again @omda07 and @mirette3 We need to have a skill called beginner mindset that will enable us to help others understand the code without making them study everything to can easily make all possible edits .
**### _
[ ] So @mirette3 and @omda07 I need an Expected time to see all these changes documented ?
_**
Login & Register & Forget Password in the Same Screen #8
The Problem :
We decide to make our code not Duplicated.
Our Solution :
We make an Index to decide the Screen
Index
Screen
0
Login
1
Register
2
Forget Password
Then we make If Condition and build TextFromField depended on Screen ex.
They told to Us it's so Good to not Duplicated our Code But this Solution is not The Best because we can't test this Code and we need to separated Widget to be easy to anyone change our code or read it.
I would Thank @youssefelgebaly about his Document about Markdown to display this issue like awesome 😊
Flutter Update 2.10 : Windows #9
Flutter 2.10 Support Windows
Today, we’re thrilled to announce the full availability of support for Windows apps for Flutter in stable builds.
The core of Flutter carries across platforms: from the portable, hardware-accelerated Skia graphics engine But desktop apps aren’t just mobile apps running on a bigger screen. They’re designed for different input devices, such as a keyboard and mouse.
The Windows implementation of Flutter combines a Dart framework and C++ engine.
We can talk to the Win32, COM, and Windows Runtime APIs either directly through Dart’s C interop layer, or using a platform plugin written in C++.
Windows support, including camera, file_picker, and shared_preferences.
There are already hundreds of packages that have been adapted to support Flutter apps built for Windows.
For a fully tailored Windows UI, you can also use packages like :
fluent_ui
flutter_acrylic
msix
Learning Process : Performance and Optimization #11
Performance
We Talk Here About :
Speed.
Memory.
App Size.
DevTools.
Speed General advice
If you are seeing janky (non smooth) animations, make sure that you are profiling performance with an app built in profile mode not in debug mode.
In Android Studio and IntelliJ, use the Run > Flutter Run main.dart in Profile Mode menu item.
Connect to a physical device Not the Emulator.
Why you should run on a real device:
Simulators and emulators don’t use the same hardware, so their performance characteristics are different.
Debug mode enables additional checks (such as asserts) that don’t run in profile or release builds.
The debug build compiles the Dart code “just in time” (JIT) as the app runs, but profile and release builds are pre-compiled to native instructions (also called “ahead of time”, or AOT) before the app is loaded onto the device. JIT can cause the app to pause for JIT compilation, which itself can cause jank.
Rebuilding far more of the UI than expected each frame. To track widget rebuilds.
Building a large list of children directly, rather than using a ListView.
Avoid overly large single Widgets with a large build() function, Split them into different Widgets.
Apply Effects Only when Needed like Opacity and Color Fillters.
Some of them invoke saveLayer() behind the scenes, which can be an expensive operation.
Why is savelayer expensive?
Calling saveLayer() allocates an offscreen buffer. Drawing content into the offscreen buffer might trigger render target switches that are particularly slow in older GPUs.
Use the Opacity widget only when necessary and we can use FadeInImage Widget or use AnimatedOpacity Widget insted of Opacity.
Clipping doesn’t call saveLayer() (unless explicitly requested with Clip.antiAliasWithSaveLayer) so these operations aren’t as expensive as Opacity, but clipping is still costly.
Avoid clipping in an animation. If possible, pre-clip the image before animating it.
Avoid pass a long Lists into Constructors.
Memory
Using memory wisely.
App Size
By default, launching your app with flutter run, or by clicking the Play button in your IDE, generates a debug build of the Flutter app. The app size of a debug build is large due to the debugging overhead that allows for hot reload and source-level debugging.
The UI thread executes Dart code in the Dart VM, When your app creates and displays a scene, the UI thread creates a layer tree, a lightweight object, and sends the layer tree to the raster thread (known as the GPU) to be rendered on the device.
Raster (known as the GPU thread) :
This thread takes the layer tree from UI and displays it by talking to the GPU (graphic processing unit), You cannot directly access the raster thread or its data, but if this thread is slow, it’s a result of something you’ve done in the Dart code.
Jank :
The frame rendering chart shows jank with a red overlay. A frame is considered to be janky if it takes more than ~16 ms to complete (for 60 FPS devices).
Figma Screens #13
On boarding Screen
welcome page display first time, when we launch the app.
it contains two buttons (for login and sign-up) and four page-view each one has animation image and two text.
Log in Screen
user open this screen to login if he already have an account.
it contains two text-field (for email and password) and two button (for login and sign-up)
Sign-Up Screen
user open this screen if he didn’t have an account.
it contains five text-field(for email,username,password,confirm password and phone) and two buttons(for signup and login)
Forget password Screen
user open this screen if he forget password.
it contains one text-filed for email and two buttons (resent password and login)
User Home Screen
home screen display when user login or sign up
it includes user courses ,recommendation courses and top courses
it contains app bar(have two icons for drawer and notifications) , flexible space (have text field and text) and three list-view.builder each one has numbers of cards (scroll in horizontal)
Drawer
drawer display in app bar include all information of user such as profile , courses,setting ..etc.
Search result
Notification screen
Profile & Edit Profile screens
It includes personal and education information.
to view profile the right screen while display and when you want to edit your profile the second screen will display.
Courses Screen
if user already enrolled in course the right screen will display other wise the left screen will display.
My Learning Screen
this screen includes my courses, tracks,wish-list courses , pending courses and archived courses.
This file includes a fixed screen to which the bottom navigation bar or the appbar can be added, and moving between more than one screen in the body
Models
This file includes models for each screen stored in the data used in this screen in short is the data warehouse that is used
Modules
This file includes screen files from widget and state management
authertication
This file includes login file, register file, forget password file and change password file
courses
This file includes two screens, one for viewing the contents of the course course_overview_screen.dart and the other for viewing the course course_details_screen.dart
my_learning
This file includes the screen of the courses that you have subscribed to
notification
This file contains the notifications screenshot
onboarding
This includes welcome screen. this screen appears when you open the app for the first time
profile
This file contains the user information and modification
search
This file includes screen appears when chick in text from filed search
home_screen.dart
This screen is the main screen in the application that appears after loging in
splash_screen.dart
This screen is the intro that shows the logo and the name of the application
shared
This includes everything that is const in the application such application themes,
component in app, and network file this include local database and remote database
C++ and Python Code #17
Problem Statement :
How to make automated testing through running some scripts
Technology Used :
Python and C++ as these are the Languages I can use Easily and Can support with them
In Python :
I used Python Requests and Json Technology to Communiate with the API
In C++ :
I used C++ CPR "CURL FOR HUMAN" and I used Nomral Libraries and An Important Hint to Run the Project you need to focus over the Makefile Technology
Setup Python3 Environment over Linux :
Installation Python3
sudo apt install python3
Installation pip3 - pip3 is the Package Installer for Python to ubuntu system to can be used from any software as Import requests :
sudo apt-get -y install python3-pip
Installation Requests - Requests is a library used for communicating over HTTP with the Server/API
pip3 install requests
For JSON : Is Normally Installed inside Python
For the IDE you can use Geany
sudo apt-get install geany
Python Code :
This code to test and register a limited number of Users to the API
Thanks to @mirette3 a miswriting words has been fixed
# Adding Libraries that we will use in our Program :
import requests
# For Importing Library Requests
import json
# For Importing Library Json
# ------------------------------------------------------------
# Test Connection to server
response = requests.get("http://10.5.62.214:8080/")
# make HTTP Get Request to check if the Server Live or Not
print(response)
# print the Response of the Server which usually will be Status 200
# ------------------------------------------------------------
# We need to start automating Register to the API
# Through Using a While Loop we will have a Counter inside that will break the loop after reaching special Number
# Through the Loop the Application will send to the Api the Needed Data using Requests Function and we will receive the response and validate it
# API need to send to it a Unique userName , Email , Phone
# So we Fixed the username and Email through a variable called Keyword
# Validation over the Phone Number is the number must be 11 Number through a Fixed Variable will changed everytime based on the counter
keyword = 'omar'
# The Variable Used to create the userName and Email
Phonee =44140002000*2
# The Variable used to create the Phone Number will call it Phonee
i=0
# Initiate the Counter
while 1:
# Starting of the Loop
# Must take in consideration the Spaces as Python Senstive for the Spaces
email=keyword+str(i)+"@[gmail.com](http://gmail.com/)"
# Create Email Variable using the Keyword and the Current counter and @gmail.com for example omar0@gmail.com
password="1111111111111"+str(i)
# Create Password Variable using a fixed string which is "1111111111111" and the Current counter
phone=str(Phonee+i)
# Create Phone Variable using the sum of Phonee and Current counter
username=keyword+str(i)
# Create username Variable using the String sum of keyword and Current counter as String which will be omar0
r = requests.post('http://10.5.62.214:8080/api/register', json={"email":email,"password":password,"phone":phone,"userName":username})
# Here Code make a POST request by sending to the API 'http://10.5.62.214:8080/api/register' a json body as mentioned above and store the response at " r "
#print(r)
# Print all the response
print(r.json())
# print the JSON Content
x=r.json()
# store the JSON Content inside new Variable
print(x['token'])
# print the attribute that have the key token
i=i+1
# Increment the Counter
if(i==1000000):
break
# Break the Loop if we reached that Number of Rounder or Users Registers
> After Downloading unzip the file and open the folder and double click on eclipse file
> Accept all Eclipse Setup for Location to be used to save projects
> From FIle > New Project > C++ Project > Cmake > Cmake Project > Give the Project name > Then hit finish
> The Reason Behind Using Cmake to can download libraries online and add them to the project meanwhile it will help you in building the project easily and can help in future to add more libraries and even export project to be executed on other devices Thanks to @KareemAhmed22 this has been added
> You will find at the left Project Explore that have 2 Main files : Your Project name .cpp and CMakeList.txt and Binaries and Build Folder
Your Code will be Inside the Your Project name .cpp
To Download Libraries Online and Use it inside your Project we will use in future CMakeList.txt
Build Folder Where the Downloaded Libraries will built with their dependences
Binaries Folder for the Executables Files
After Understanding Eclipse Let's Add our Library " cpr C++ "
First of All Visit this repo on github as this library we are going to use and have a look at readme :
https://github.com/libcpr/cpr
You will find out Label for Usage :
You will find some CMakeList.txt Scripts
You will copy them and paste at your CMakeFile.txt at your project inside Eclipse
Below is my CMakeFile.txt you can use it directly but Every Omar Word Replace it in the next code with your Project name
cmake_minimum_required (VERSION 2.6)
project (omar)
add_executable(omar omar.cpp)
include(FetchContent)
FetchContent_Declare(cpr GIT_REPOSITORY https://github.com/libcpr/cpr.git
GIT_TAG beb9e98806bb84bcc130a2cebfbcbbc6ce62b335) # The commit hash for 1.7.2. Replace with the latest from: https://github.com/libcpr/cpr/releases
FetchContent_MakeAvailable(cpr)
target_link_libraries(omar PRIVATE cpr::cpr)
Important
You will face Problem to Make the CMakeFile.txt with each build to ensure that any update their will bounce direct back to your project.
To Solve This Check the Stackoverflow Issue and Try to follow it .
After this. When you are going to run the Project This will run automatic to ensure all libraries are supplied and up to date
C++ Code :
// Libraries Used in the Code
#include <iostream>
// Standard Library for Input Output Operations
#include <cpr/cpr.h>
// Our Main Library for Communication with the API
#include <string>
//Handling the Strings in the Code
#include <thread>
// To make Threads to run Features Parallel
#include <sstream>
// we used it here to can Make stream to store the Phone Number then Transform it to String as Setpercision function works only with streams
#include <iomanip>
// to can use setprecision function to work to can get the float without decimal point
using namespace std;
// Using the Standard Namespace
// Main Function Used to register Accounts
// This Fucntion take 3 Variables :
// The first Variable : Keyword which is the keyword that will manipulate the Username and Email
// The Second Variable : is K which is used for Creating Phone Number
// The Third Variable : is the Number of Iteration needed to be done
void omar (string keyword,double k,int iteration)
{
// the loop that will help with register all needed users
for(int i = 0 ; i < iteration;i++)
{
stringstream stream;
// This is to make a new string stream object called stream
stream << std::fixed << setprecision(0) << i+k;
// Here we are saving at stream tha sum of i + k but taking in consideration that the percision is 0 which means no decimel point and std::fixed is for keep the accuracy of our double or float to 6 digits after the decimel.
string phone = stream.str();
// Save at a new variable called phone the string saved in stream
string body = "{\"userName\":\""+keyword+to_string(i)+"\",\"email\":\""+keyword+to_string(i)+"@gmail.com\",\"password\":\"abdeceasdasd\",\"phone\":\""+phone+"\"}";
// Here we store the json generated order to can send it in variable called Body
auto r = cpr::Post(cpr::Url{"http://10.5.62.214:8080/api/register"}
,
cpr::Header{{"Content-Type","application/json"}}
,
cpr::Body{body});
// Here in cpr we use it to make POST request by giving it the Url that we are going to use which is http://10.5.62.214:8080/api/register
// By Giving to cpr too that the header is Application Json and then send in the bodd the body we created
// cout<<r.text <<endl;
}
}
int main(int argc, char **argv) {
// To make the Program run multiple times parallel we start using Threads
// Next we will initiate 8 Threads
// thread working like this
// thread name_of_tread(function_you_are_going_to_run , function Variables )
thread th1(omar, "xxxx",19091222334,1000);
thread th2(omar, "xxxxx",29094222334,1000);
thread th3(omar, "xxxxxx",39066222334,1000);
thread th4(omar, "xxxxxxx",49042223341,1000);
thread th5(omar, "xxxxxxxx",50042223341,1000);
thread th6(omar, "xxxxxxxxx",60042223341,1000);
thread th7(omar, "xxxxxxxxxx",70042223341,1000);
thread th8(omar, "xxxxxxxxxxx",80042223341,1000);
// Here we start launching the Threads
th1.join();
th2.join();
th3.join();
th4.join();
th5.join();
th6.join();
th7.join();
th8.join();
// THe program Automatic will close after finishing all threads
return 0;
}
After Adding this code to your project in your C++ File inside Eclipse you will need to start Compile and Run it :
First you will need to build your Project and then Run it and TaDaaaaa You are Live :)
Build Login , Courses Features and Automate all Features
Standardize all the Features as the Program will run Based on an Input from JSON file (Configuration FIle) to can run each feature based on different inputs that C++ Program will read automatically and start implementing it
Generate Reports and Compare with Expectations to Generate Pass or Fail Reports
what is git and github?
why you must learn git?
Before using GIT we need to understand some Definitions :
Repository
is a storage that keep date organized and a community can access this data.Master
is a main of data .Branch
This is usually used with teams so that there is no conflict in the data (each member in team have own branch and in the end combination them in the master) .init
when you start your first time with git you can add your username with git and email that will be used with push .Add
to add files that are ready to be commited .Commit
(snapshot or checkpoint) is to submit all changes that you do to your added files to be ready to be pushed to your server move it in local repositiory .Status
to check what the file added and not commited.Remote
to connect the local repo and the repo on server .Push
upload local changes to remote.pull
you pull changes from remote repo to your local.pull request
tell other about changes to pull it from local to remote .Clone
copy of the repositiory origin to your local Device .Fetch
copy a branch and save it as a new branch to your device .Git branch
get all branches in your repository.git branch Name
create a new branch with a Name.Checkout
is to move between branches.this is all stages
so to add the code to our ssh protocol on our Ubuntu
to Get a copy from the RSA code to add to my gitlab server side We need to install
to take a copy to your clipboard
Commands Usually Used in Git
1. Git clone
2. Git branch
3. Git checkout
4. Git status
5. Git add
6. Git commit
7. Git push
8. Git pull
The git pull command is used to get updates from the remote repo. git pull
9. Git merge
The git pull command is used to get updates from the remote repo. git pull
source Link "https://www.freecodecamp.org/news/10-important-git-commands-that-every-developer-should-know/"
How to restore old versions ?
cd ~/git/your-repo-root git log
find the commit id you want
git checkout .
IMPORTANT NOTE: the trailing
.
in the previous line is important!git commit -m "Restoring old source code"
How to Compare files ?
source Link "https://stackoverflow.com/questions/10988757/git-compare-files-before-commit"
How to merge with Master ?
What is the Normal Process to start working on a new Feature ?
create a new branch git branch
steps
pull requests
Pull requests let you tell others about changes you've pushed to a branch in a repository on GitHub. Once a pull request is opened, you can discuss and review the potential changes with collaborators and add follow-up commits before your changes are merged into the base branch.
Steps
GitHub Actions
Automate, customize, and execute your software development workflows right in your repository with GitHub Actions. You can discover, create, and share actions to perform any job you'd like, and combine actions in a completely customized workflow.
Video Link
First how work git in Android Studio
![image](https://user-images.githubusercontent.com/61950354/1# GitHub Actions Automate, customize, and execute your software development workflows right in your repository with GitHub Actions. You can discover, create, and share actions to perform any job you'd like, and combine actions in a completely customized workflow.
Video Link "https://www.youtube.com/watch?v=cP0I9w2coGU&t=161s"53848368-69f6e0af-4a00-44e1-af5e-7a4e00a3f4a0.png)
if you do not have git in your pc
and go to Github
create an account , enter your data and select your account
go to your account in github and click on repositories
create a new repository
enter your name of repo
clicked in create repository
and open terminal on your project in android studio Or cmd (cd your project path ) and add this lines line by line
finally you upload your project in github .
Next How to work in each Branch ?
and create a new file if you want
add git status to know what files not added yet.
add all files
and git status one more time to get files add but not commit yet.
.
and then add commit
finally push your code in your new branch using this commit
go to your github account
if you want merge this branch in master
First of All We need to add (ssh Key) in your PC
Second Things : Start to Clone Project
Third Thing : Start to Make Your Branch and Add Your files
To Make your Branch:
Switch to your branch:
Very Important
To Show what's changed in your Project:
After you Show Your Edit's to your branch add them to Local Storage to Commit:
Make a Commit to your branch (Like a Message to know what changed):
Push your commit to your branch:
Before Push Please, checkout to check you on your branch
How to Add SSH in Windows
install Git Bash in your Windows.
Run :
Then Run and Copy SSH and Go to your Account and add it.
Testing
What is testing ?
the execution of software and trying all its functions and properties in different ways and to examine all the possibilities that user may carry out while executing the software.
What are objectives we do testing?
Software Testing Myths?
We have a Bug but what is the Bug?
Is The deviation of the actual result from the expected result.`
A person makes an Error That produce a Fault or a Bug in the program code. that might causes a failure in the software.
Software Requirement Specification
Is detailed description (purpose, overall description, system feature, interface requirements) the main reference for Expected result
If there is no SRS:
Test Inputs
Bug Addressing
What is it? Bug reporting >> Fixing bug >>Recheck it is bug free and there is no bug introduced. How? on Bug Tracking System.
Test Suite: is Test cases of the same module by Test Procedure which is Test Execution all Test Steps if: pass AR==ER fail AR!=ER block no possibility to test
Test Case Documentation:
maintainability of test case :
we need the simplicity and easy of changing a test case.
Avoid those test case practices:
4 levels of Testing - comparison
1. Unit Testing. component, module or unit testing.
To ensure that every unit is doing its function as it in specifications.
2. Integration Testing.
3. System Testing.
4. Acceptance Testing. _ achieve the business needs of End User
Scaffolding
Driver>>Tested Unit>>stub. Driver: used in Bottom UP Testing to test low level functions or modules. Stub: used in Top Down Testing . steps:
Reasons for Test Cases
Test Design Techniques
why? To design the suitable test cases for each type and part of software, Write the right number of test cases to cover all code possibilities and write minimum number effective number of test cases . types:
Black Box Testing Techniques. == 'Specification based testing'
Applies foe functional and non-functional testing, without reference to the internal structure of the system. with: mainly applicable to higher levels of testing (System Testing and Acceptance Testing). types:
1. Equivalence Partitioning(EP)
2. Boundary value analysis (BVA)
3. Decision Table
4. State Transition.
5. Use case technique.
White Box Testing Techniques. =='Glass box Testing or Structure base Testing'
Testing based on an analysis of the internal structure of the component or system. with: mainly applicable to lower levels of testing (Unit Testing or integration testing).
1. Statement Testing
2. Desertion Testing
Statement test cases for a segment of code will always =< of Branch / Decision test cases. Branch/decision testing is a more complete form of testing than statement testing.
Why is Testing imporant? What is Testing?
Testing Principles
Fundamental Test Process
Fundamental Test process
psychology of testing code of Ethics
Testing throughout software life cycle SDLC models:
1. Sequential model.
1. Waterfall.
Disadvantages:
2. V-model.
Advantages:
Disadvantage:
2. Iterative model. dividing the SDLC to mini SDLC with regression testing
3. Incremental model. _Sequential and alterative
Verification Testing and validation Testing
Verification: Requirements. Validation: propose customer needs
Testing types
1. Functional Testing (Black Box)
2. Non-Functional Test How the System works? SW characteristics
3. Structure testing (white Box) with all Testing levels specially unit testing and integrated testing
4. Testing Related to Change types:
5. Maintenance-Testing
with all testing types and testing level why
Impact Analysis
determine the the extent of effect on system and how much regression testing to do.
Static Techniques
Dynamic Testing
code execution high coast and long time
SRSD
SD, Use cases, UML diagram
SW Testing life cycle STLC
Requirement Analysis.
Test Planning. Test plan Document.
Test Case Development.
Environment setup.
Test Execution.
Test case writing
Test case definition : _IEEE: Documentation of specified inputs or predicted result, A group of activates which have expected results and actual results happen in a certain sequence in order to check the specification and advantage of the product.
The sources of Test Cases:
Test Case Format
Test case attributes :
Test case ID. Unique identifier
Test case Title/Description. short description of test case & should be effective to convey the test case
Test case Summary. Detailed description of test case & additional information needed for the test case to execute.
Pre-condition/Assumption. any pre-requisite required to excite the test case.
Any user data dependency
Dependencies on test environment
special setup
dependencies on any anther test cases
Test Steps Actual step to be followed or executed.
Test Data. data that us used.
Excepted Result.
Actual result.
Test case states. pass/fail/not applicable.
Comments.
Test case Priority -(Critical/high/medium/low).
Bug reports
Bug life cycle
Bug Statuses
Experience-based techniques
informal
This picture is show a list of Testing Technique :
Test Management
How To Install Software Needed
Install git
How to Install Android Studio on Ubuntu
Minimum System Requirements:
Installing Java for Android Studio:
Before you install the Android Studio IDE, you need to make sure your Ubuntu installation is armed and ready with the recommended Java development kit for Android Studio – Oracle JDK.
To check the version of Java
If you don’t have Java installed, the output should be something like:
Note: Make sure that you have updated the Advanced Package Tool (APT) before you move forward to install OpenJDK.
Install OpenJDK on Ubuntu
All you have to do now is to set the “JAVA_HOME” and “PATH” environment variables and then you are done.
Save the bash file, restart the terminal, and type echo $JAVA_HOME to make sure the path is properly set.
Installing Android Studio From The Ubuntu Software Center
Locate the Ubuntu Software Center icon in your taskbar and use the search functionality to find Android Studio. Click install and let it download and run initial setup.
Install Flutter SDK on Ubuntu
System requirun the following command to begin signing licenses. rements
Install Flutter using snapd
use the following command to display your Flutter SDK path:
Run flutter doctor
Install Android SDK Command-line Tools (latest)
On your Android Studio Project, click on the File and then “Settings“.
Select Appearance & Behavior > System Settings > Android SDK > SDK Tools
Check the box given for “Android SDK Command-line Tools (latest)” and then press the OK button
Agree to Android Licenses
Before you can use Flutter, you must agree to the licenses of the Android SDK platform. This step should be done after you have installed the tools listed above.
Make sure that you have a version of Java 8 installed and that your JAVA_HOME environment variable is set to the JDK’s folder.
Android Studio versions 2.2 and higher come with a JDK,
run the following command to begin signing licenses.
Set up an editor
Backend
Install Node.js and npm
Node JS
Install Visual studio code
Install MongoDB
How to git project from GitHub
Which libraries you used through the development process?
bcrypt
to encrypt the passwordexprss js
express async errors
to handle any error async like connect to DBjoi
to validate the inputsjsonwebtoken
to generate token that have user infomongoose
it’s the databaselodash
to take just input that neededwinston
to save the errors in log in filewinston-mongodb
to save the errors in log in the databasecompression
to compress the requestpackages in development environment
The code is fully documented
7 Learning Process: State Management (Riverpod)
Riverpod
A state-management library that:
For widgets to be able to read providers, we need to wrap the entire application in a "ProviderScope" widget.
Providers
Providers are the most important part of a Riverpod application. A provider is an object that encapsulates a piece of state and allows listening to that state.
Creating a provider
in Riverpod we can have two providers expose a state of the same "type":
Provide data:
Provider
Future provider
Stream provider
State provider
Advantages
allows us to easily create, access, and combine providers with minimal standard code.
caching the data in memory
Install RiverPod
-add the latest version of flutter_riverpod as a dependency to our (pubspec.yaml) file. -wrap our root widget in void main with a ProviderScope.
Steps to Create a provider
1- add Global provider
2- read the provider value inside the widget, we have two ways:
Note
to avoid caching data in memory we can use autoDispose
watch function interact with the reference of the provider.
Riverpod
to Installing this package
Import it
wrap MyApp "ProviderScope" widget
Create a Provider
Consume the Provider // in this case rebuild all widget
or
Consume the Provider // in this case build specific widget Text Only
Type of Provider
Advantages of RiverPod
BackEnd #3
We need to Document ( Installation - Usage - Hello World Example - Links for DOcumentation for each one ) : 1)Node JS Installation https://nodejs.org/en/docs/guides/getting-started-guide/
1) Express JS Installation • mkdir myapp • cd myapp • npm init • npm install express –save Hello world Example https://expressjs.com/en/starter/hello-world.html
2) MongoDB Installation for ubuntu • wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add - • sudo apt-get install gnupg • echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list • sudo apt-get update • sudo apt-get install -y mongodb-org
Installation for windows • https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/
3) IDEs
From Where you start to Learn these tools?
Tutorial Node js
Documentation Node js Docs
Tutorial Express js Documentation Express js Docs
Arabic tutorial API Tutorial
English Crash Course API Tutorial en
Which libraries you used through the development process?
bcrypt
to encrypt the passwordexprss js
express async errors
to handle any error async like connect to DBjoi
to validate the inputsjsonwebtoken
to generate token that have user infomongoose
it’s the databaselodash
to take just input that neededwinston
to save the errors in log in filewinston-mongodb
to save the errors in log in the databasecompression
to compress the requestpackages in development environment
dotenv
to store constant strings like database URL connectionmodemon
when click on ctrl + s restart the server automaticallyStructure of code
there are 5 folders
config
folder for save errors lognode_modules
built in generated that have packages filesmiddleware
models
for schema modelsroutes
for rest api (Request , Response)there are 5 files
.env
to store constant values.gitignore
to ignore files not upload them to githuberror.log
that have errors logspackage-lock
built in generated that have packages codepackage
have project information and dependence of packagesserver
file that begin start when the project rundownload backend project
Import Backend project to Visual studio code IDE
File
→OpenFloder
→Choosing the project from the device
Run the project on a local Server
package.js
fileHTTP response status codes
For example:
Build Server
// copmresed requests app.use(compression())
// import register const usersRegister = require('./routes/register') app.use('/register', usersRegister) // import login const usersLogin = require('./routes/login') app.use('/login', usersLogin) // import profile const userProfile = require('./routes/profile') app.use('/profile', userProfile) // import changepassword const changePassword = require('./routes/changePassword') app.use('/api/changePassword', changePassword) // import courses const newCourse = require('./routes/courses') app.use('/api/course', newCourse)
// if write invalide url or end point send to user an error message app.all('*', (req, res, next) => { res.status(404).json({ status: 'false', message: 'Page not found !' }) }) // listen on port 8080 local host app.listen(8080, () => logger.info('server started 8080 ....'))
Schema validation using joi package
You can add or remove any attribute from your schema
regex(/[a-zA-Z]/) to begin with char
}
Build Registration
Use validate function
email
if (user) { return res.status(200).json({ status: 'false', message: 'email already in use' }) }
If validate then
Build Login
Take inputs from user for example
const { email, password: plainTextPassword } = req.body
you can change any attributes independent on schema's required attributesUse validate function
check in database by any required attribute you want from schema for example by
email
You can change any required attribute from schema then change the message.
If validate then
Build middleware
authentication middleware
check if user have token (auth)
getCourses middleware
Change Password
change password inside the app for user that logged in
Build Profile
middleware auth check first if user logged in and have a token
Build Course Schema
to do this we need to take a reference from user schema
@omda07 I am still waiting as we agreed yesterday to have some Examples based on each questions to understand what exactly to change for example :
check in database by any required attribute you want from schema for example by email let user = await Users.findOne({ email }).lean()
if (user) { return res.status(404).json({ status: 'false', message: 'email already in use' }) }
You can make it like :
let user = await Users.findOne({ username }).lean()
if (user) { return res.status(404).json({ status: 'false', message: 'email already in use' }) }
To change the feedback message you can change here from
if (user) { return res.status(404).json({ status: 'false', message: 'email already in use' }) }
to if (user) { return res.status(404).json({ status: 'false', message: 'Hi, This is an Error' }) }
What is the 10 here ? You need to clear in the comments of the code what is each value refer to
userName: { type: String, required: true, minlength: 3, maxlength: 44 }, email: { type: String, required: true, maxlength: 254 },
How can I add more validation to ensure for example : 1) the Username can't start with Sympols or Numbers 2) Username can't have spaces 3) Username can't be duplicated like email Live while I am writing on Flutter GUI I validate if this username is used before In the database or not . To make it more clear I am writing first char "O" this less than 3 Paramters the FLutter Team will Raise flag that is less than 3 Char but after haveing for example "OOO" how we check instant without click on registration button and send that this username is booked from example . 4) In username is "OOO" is different from "ooo" is the validation function compare with taking in consideration the Capital of the Chars ?
}).options({ abortEarly: false });
What is this line refer to ?
https://github.com/omarokasha1/TheFirstProject/blob/186e8bbef167fa6f0cbbd9b7fcc79bffa3498e77/loginAndRegister/server.js
Where is the documentation / Comments for this Code ?
After Have a some time in the backend code here is my Thoughts :
It is Very Important @omda07 and @mirette3 to have next Documentation : 1) What is the Structure of the Code 2) What is automatic Generated by tools and We didn't edit or Developed anything at and What we changed in some files and what we developed ? 3) I can see that in this path https://github.com/omarokasha1/TheFirstProject/tree/backend/loginAndRegister we have 5 Folders and 5 FIles what is the usage from each one ? 4) What is these status Numbers ? What are they referring to ? we need a table with the definition of each number . 5) We need a table of definition that will have a keyword like subscriber ? 6) Check Change Password Code , you need to make a lot of comments with some questions like :
Again @omda07 and @mirette3 We need to have a skill called beginner mindset that will enable us to help others understand the code without making them study everything to can easily make all possible edits .
**### _
_**
Login & Register & Forget Password in the Same Screen #8
The Problem :
We decide to make our code not Duplicated.
Our Solution :
We make an Index to decide the Screen
Then we make If Condition and build TextFromField depended on Screen ex.
After Ask Experts :
They told to Us it's so Good to not Duplicated our Code But this Solution is not The Best because we can't test this Code and we need to separated Widget to be easy to anyone change our code or read it.
I would Thank @youssefelgebaly about his Document about Markdown to display this issue like awesome 😊
Flutter Update 2.10 : Windows #9
Flutter 2.10 Support Windows
Today, we’re thrilled to announce the full availability of support for Windows apps for Flutter in stable builds.
The core of Flutter carries across platforms: from the portable, hardware-accelerated Skia graphics engine But desktop apps aren’t just mobile apps running on a bigger screen. They’re designed for different input devices, such as a keyboard and mouse.
The Windows implementation of Flutter combines a Dart framework and C++ engine.
We can talk to the Win32, COM, and Windows Runtime APIs either directly through Dart’s C interop layer, or using a platform plugin written in C++.
Windows support, including camera, file_picker, and shared_preferences.
There are already hundreds of packages that have been adapted to support Flutter apps built for Windows.
For a fully tailored Windows UI, you can also use packages like :
fluent_ui
flutter_acrylic
msix
Learning Process : Performance and Optimization #11
Performance
We Talk Here About :
Speed.
Memory.
App Size.
DevTools.
Speed General advice
If you are seeing janky (non smooth) animations, make sure that you are
profiling performance
with an app built inprofile mode
not indebug mode
.In Android Studio and IntelliJ, use the
Run > Flutter Run main.dart in Profile Mode
menu item.Connect to a physical device Not the Emulator.
Why you should run on a real device:
Simulators and emulators don’t use the same hardware, so their performance characteristics are different.
Debug mode enables additional checks (such as asserts) that don’t run in profile or release builds.
The debug build compiles the Dart code “just in time” (JIT) as the app runs, but profile and release builds are pre-compiled to native instructions (also called “ahead of time”, or AOT) before the app is loaded onto the device. JIT can cause the app to pause for JIT compilation, which itself can cause jank.
Rebuilding far more of the UI than expected each frame. To track widget rebuilds.
Building a large list of children directly, rather than using a ListView.
Avoid overly large single Widgets with a large build() function, Split them into different Widgets.
Apply Effects
Only
when Needed likeOpacity
andColor Fillters
.Some of them invoke
saveLayer()
behind the scenes, which can be an expensive operation.Why is
savelayer
expensive?Calling
saveLayer()
allocates an offscreen buffer. Drawing content into the offscreen buffer might trigger render target switches that are particularly slow in older GPUs.Use the
Opacity
widget only when necessary and we can use FadeInImage Widget or useAnimatedOpacity
Widget insted of Opacity.Clipping doesn’t call
saveLayer()
(unless explicitly requested withClip.antiAliasWithSaveLayer
) so these operations aren’t as expensive as Opacity,but clipping is still costly
.Avoid clipping in an animation. If possible, pre-clip the image before animating it.
Avoid pass a long Lists into Constructors.
Memory
Using memory wisely.
App Size
By default, launching your app with flutter run, or by clicking the Play button in your IDE, generates a debug build of the Flutter app. The app size of a debug build is large due to the debugging overhead that allows for hot reload and source-level debugging.
Checking the total size:
We should Run in the Terminal
or
Estimating total size:
Android:
Follow the Google Play Console’s instructions for checking app download and install sizes.
Produce an upload package for your
Log into your Google Play Console. Upload your application binary by drag dropping the .aab file.
Finally View the application’s download and install size in the Android vitals -> App size tab.
NOTE:
download sizes may vary depending on their hardware.Breaking down the size:
The size analysis tool is invoked by passing the --analyze-size flag when building:
Some other things you can do to make your app smaller are:
Remove unused resources.
Minimize resource imported from libraries.
Compress PNG and JPEG files.
DevTools
What is DevTools?
DevTools is a suite of performance and debugging tools for Dart and Flutter.
What can I do with DevTools?
Inspect the UI layout and state of a Flutter app.
Diagnose UI jank performance issues in a Flutter app.
CPU profiling for a Flutter or Dart app.
Network profiling for a Flutter app.
Debug memory issues in a Flutter or Dart command-line app.
Analyze code and app size.
How do I install DevTools?
See the Android Studio/IntelliJ, VS Code, or command line pages for installation instructions.
Flutter frames chart :
UI :
The UI thread executes Dart code in the Dart VM, When your app creates and displays a scene, the UI thread creates a layer tree, a lightweight object, and sends the layer tree to the raster thread
(known as the GPU)
to be rendered on the device.Raster (known as the GPU thread) :
This thread takes the layer tree from UI and displays it by talking to the GPU (graphic processing unit), You cannot directly access the raster thread or its data, but if this thread is slow, it’s a result of something you’ve done in the Dart code.
Jank :
The frame rendering chart shows jank with a red overlay. A frame is considered to be janky if it takes more than ~16 ms to complete (for 60 FPS devices).
Figma Screens #13
On boarding Screen
welcome page display first time, when we launch the app. it contains two buttons (for login and sign-up) and four page-view each one has animation image and two text.
Log in Screen
user open this screen to login if he already have an account. it contains two text-field (for email and password) and two button (for login and sign-up)
Sign-Up Screen
user open this screen if he didn’t have an account. it contains five text-field(for email,username,password,confirm password and phone) and two buttons(for signup and login)
Forget password Screen
user open this screen if he forget password. it contains one text-filed for email and two buttons (resent password and login)
User Home Screen
home screen display when user login or sign up it includes user courses ,recommendation courses and top courses it contains app bar(have two icons for drawer and notifications) , flexible space (have text field and text) and three list-view.builder each one has numbers of cards (scroll in horizontal)
Drawer
drawer display in app bar include all information of user such as profile , courses,setting ..etc.
Search result
Notification screen
Profile & Edit Profile screens
It includes personal and education information. to view profile the right screen while display and when you want to edit your profile the second screen will display.
Courses Screen
if user already enrolled in course the right screen will display other wise the left screen will display.
My Learning Screen
this screen includes my courses, tracks,wish-list courses , pending courses and archived courses.
Account setting screen
to change password open this screen
Author Courses
Create Courses & modules
my courses , tracks , modules
Author public profile
How do pages communicate with each other
Flutter Documetation Task #15
The Flutter Code Structure
Naming method
Rely on small letters and separate words with
_
layout file
This file includes a fixed screen to which the bottom navigation bar or the appbar can be added, and moving between more than one screen in the body
Models
This file includes models for each screen stored in the data used in this screen in short is the data warehouse that is used
Modules
This file includes screen files from widget and state management
authertication
This file includes login file, register file, forget password file and change password file
courses
This file includes two screens, one for viewing the contents of the course
course_overview_screen.dart
and the other for viewing the coursecourse_details_screen.dart
my_learning
This file includes the screen of the courses that you have subscribed to
notification
This file contains the notifications screenshot
onboarding
This includes welcome screen. this screen appears when you open the app for the first time
profile
This file contains the user information and modification
search
This file includes screen appears when chick in text from filed search
home_screen.dart
This screen is the main screen in the application that appears after loging in
splash_screen.dart
This screen is the intro that shows the logo and the name of the application
shared
This includes everything that is const in the application such application themes, component in app, and network file this include local database and remote database
C++ and Python Code #17
Problem Statement :
How to make automated testing through running some scripts
Technology Used :
Python and C++ as these are the Languages I can use Easily and Can support with them
In Python :
In C++ :
Setup Python3 Environment over Linux :
Installation Python3
Installation pip3 - pip3 is the Package Installer for Python to ubuntu system to can be used from any software as Import requests :
Installation Requests - Requests is a library used for communicating over HTTP with the Server/API
For JSON : Is Normally Installed inside Python
For the IDE you can use Geany
Python Code :
This code to test and register a limited number of Users to the API
Thanks to @mirette3 a miswriting words has been fixed
------------------------------------------------------------
Setup C++Environment over Linux :
Installation gcc
Installation g++
Installation eclipse for C++
>
Visit the URL Below
>
Search for Eclipse for C++
>
Download Linux [x86_64]
>
After Downloading unzip the file and open the folder and double click on eclipse file
>
Accept all Eclipse Setup for Location to be used to save projects
>
From FIle > New Project > C++ Project > Cmake > Cmake Project > Give the Project name > Then hit finish
>
The Reason Behind Using Cmake to can download libraries online and add them to the project meanwhile it will help you in building the project easily and can help in future to add more libraries and even export project to be executed on other devices Thanks to @KareemAhmed22 this has been added
>
You will find at the left Project Explore that have 2 Main files : Your Project name .cpp and CMakeList.txt and Binaries and Build Folder
After Understanding Eclipse Let's Add our Library " cpr C++ "
First of All Visit this repo on github as this library we are going to use and have a look at readme :
You will find out Label for Usage :
You will find some CMakeList.txt Scripts
You will face Problem to Make the CMakeFile.txt with each build to ensure that any update their will bounce direct back to your project.
To Solve This Check the Stackoverflow Issue and Try to follow it .
After this. When you are going to run the Project This will run automatic to ensure all libraries are supplied and up to date
C++ Code :
After Adding this code to your project in your C++ File inside Eclipse you will need to start Compile and Run it :
Enjoy!
------------------------------------------------------------
For Future Development :
C++ Project.zip