Monday, December 6, 2021

How to restart the node server after the change in the typescript files in Node Express Server development?

 usually we can use the following configuration in the Package.json file to run the node server with nodemon.

"start:dev": "nodemon --watch './**/*.ts' --exec ts-node src/index.ts"

how the above command will required additional configuration for the nodemon.

ts-node-dev will provide us much better experience since there is not setup configuration. we can simply execute the command below to start the node express server and any change is made the server will automatically recompile and restart.

 "dev": "ts-node-dev src/index.ts"

However you must install the ts-node-dev package to run the command

yarn add ts-node-dev

Thursday, December 2, 2021

how to delete all node_modules in the current directory?

 when you have a specific folder to store all react projects, then there will be lots of spaces being occupied by the node_modules folder.

we can easily execute the following command to free up the space for any projects not currently working on.

E:\Code

FOR /d /r . %d in (node_modules) DO @IF EXIST "%d" rm -rf "%d"


Friday, November 12, 2021

how to enable .Net 6.0 hot reload in Visual Studio Code?

 Hot Reload is a cool feature in .Net 6. we can easily enable this feature in Visual Studio Code with executing the following command 

dotnet watch run 

then we do not have to rerun the dotnet run to recompile the whole application to see the change immediatley.


 

Monday, October 4, 2021

10 best Nuget Package for .Net Developer

Most .NET Developer should love to  integrate the following package in their .NET project developer.

xUnit & NUnit : pacakge for unit testing

Moq & NSubstitute: Mocking libaries for .Net testing

Polly: Provide rich features for policies handling

FluentAssertions: Provide  rich features for Assertions

BenchmarkDotNet: Provider Performance trace

Serilog: Provide logging with full structure events

Autofixture & Bogus : Fake Data Generator

Scrutor: add scanning capabilities to the default Microsoft Extensions. (DependecyInjection DI Container)

Automapper:Object to Object mapper

Dapper & Entity Framework Core: Data Access framework: Dapper is simple and customable

MediatR & Brighter : CQRS stands for Command Query Responsibility Segregation libraries. MediatR is an in-process command dispatcher. Brighter is an out of process command dispatcher

FluentValidation: validation library using fluence interface and lamda expression for building validation rules

Refit & RestSharp: API tools. Refit is an automatic type-safe REST library for .Net. RestSharp is a simple REST and HTTP API Client for .Net.

Json.NET: handle json data


Friday, October 1, 2021

Immediate Git Commands

a list of handy git commands

# check the change of the file 

git diff filename

# check in parital change of the file -p flag will show us the change in patch level

git add -p filename

# use git commit to enter the concise message

git commit 

# use git log to check the commit history to ensure the change had been commit

git log

# create a branch   

git branch test

# use the branch

git checkout test

# push the change back to the repository

git push --set-upstream origin test

# merge the change

git merge test

# undo the merge and rebase

git merge --abort

git rebase--abort

#use mergetool to perform the merge

git mergetool




Monday, September 13, 2021

How to fix "HTTP Error 404.0 - Not Found" in Kubernetes ingress-nginx services?

i had setup the kubernetes Ingress with ingress-nginx with the following code, in my local machine,

which will direct the traffic to the backend service in kubernetes

apiVersionnetworking.k8s.io/v1
kindIngress
metadata:
  nameingress-srv
  annotations:
    kubernetes.io/ingress.classnginx
    nginx.ingress.kubernetes.io/use-regex"true"
spec:
  rules:
    - hostacme.com
      http:
        paths:
          - path/api/platforms
            pathTypePrefix
            backend:
              service:
                nameplatformservice-clusterip-srv
                port:
                  number80
          - path/api/c/platforms
            pathTypePrefix
            backend:
              service:
                namecommandservice-clusterip-srv
                port:
                  number80

after the setup is complete. i try to browse to the platform service web api which is hosted in the backend server.

http://acme.com/api/platforms/  but the error comes up immediately, which indicated that 

  • The directory or file specified does not exist on the Web server.

since the directory was not hosted in the IIS, it had been deployed to the pods in the kuberentes


As we manipulate the kubernetes in the local environment, we can check what process is using the port 80

C:\code\dotnet-microservices\k8s>netstat -ano | findstr ":80" | findstr "LISTENING"

  TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       4

  TCP    0.0.0.0:8081           0.0.0.0:0              LISTENING       4

  TCP    [::]:80                [::]:0                 LISTENING       4

  TCP    [::]:8081              [::]:0                 LISTENING       4


the PID 4 represnet that the port 80 had been assigned to IIS local host.  we should stop the World Wide Web Publishing Service, in order to release the port 80 for Kubernetes services. 



after I stop the World Wide Web Publishing Service, the we can see that port 80 had been assigned to different processes.

C:\code\dotnet-microservices\k8s>netstat -ano | findstr ":80" | findstr "LISTENING"

  TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       3440

  TCP    [::]:80                [::]:0                 LISTENING       3440

  TCP    [::1]:80               [::]:0                 LISTENING       16096

Now we should be able to access the web api host in the kubernetes.

[{"id":1,"name":"dotnet","cost":"free","publisher":"Microsoft"},{"id":2,"name":"SQL Server Express","cost":"free","publisher":"Microsoft"},{"id":3,"name":"Kubernetes","cost":"free","publisher":"Cloud Native Computer Foundation"}]







Friday, September 10, 2021

how to fix "The SSL connection could not be established," in Web Api development with ASP.Net Core and .Net 5.0

I implemented two MicroServices in my local machine,  I try to call one service from another with HttpClient. the error was shown as blew after the service call.

"cound not send data to commandservice with errror The SSL connection could not be established, see inner exception. System.Security.Authentication.AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot   at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)

   at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)"

the error indicated that th SSL connection cannot be established due to certificate issue.

we can the  use the following command to trust the self-singed certificate

dotnet dev-certs https --trust

for more information about this command you can check out the microsoft document website with the link below


https://docs.microsoft.com/en-us/dotnet/core/additional-tools/self-signed-certificates-guide

how to fix "Unable to connect to the server: dial tcp: lookup myaksclust-myresourcegroup-3f2c36-40a876eb.hcp.eastus.azmk8s.io: no such host" error?

when I try to check the version of Kubectl with kubectl version that is installed in my local desktop. i got the following error

"Unable to connect to the server: dial tcp: lookup myaksclust-myresourcegroup-3f2c36-40a876eb.hcp.eastus.azmk8s.io: no such host"

I check the kubectl configuration file with Kubectl config view

it shows with information below

apiVersion: v1                                                                                                                                       

clusters:                                                                                                                                            

- cluster:                                                                                                                                           

    certificate-authority-data: DATA+OMITTED                                                                                                  

    server: https://aks-cluste-aks-rg-3f2c36-a86fa58c.hcp.eastus.azmk8s.io:443                                                                       

  name: aks-cluster                                                                                                                                  

- cluster:                                                                                                                                           

    certificate-authority-data: DATA+OMITTED                                                                                                         

    server: https://kubernetes.docker.internal:6443                                                                                                  

  name: docker-desktop                                                                                                                               

- cluster:                                                                                                                                           

    certificate-authority-data: DATA+OMITTED                                                                                                         

    server: https://kuar-clust-kuar-3f2c36-3176b3bf.hcp.eastus.azmk8s.io:443                                                                         

  name: kuar-cluster                                                                                                                                 

- cluster:                                                                                                                                           

    certificate-authority: C:\Users\admin\.minikube\ca.crt                                                                                           

    server: https://192.168.2.14:8443                                                                                                                

  name: minikube                                                                                                                                     

- cluster:                                                                                                                                           

    certificate-authority-data: DATA+OMITTED                                                                                                         

    server: https://myaksclust-myresourcegroup-3f2c36-40a876eb.hcp.eastus.azmk8s.io:443                                                  

  name: myAKSCluster                                                                                                                                

contexts:                                                                                                                                            

- context:                                                                                                                                           

    cluster: aks-cluster                                                                                                                             

    user: clusterUser_aks-rg_aks-cluster                                                                                                             

  name: aks-cluster                                                                                                                                  

- context:                                                                                                                                           

    cluster: docker-desktop                                                                                                                          

    user: docker-desktop                                                                                                                             

  name: docker-desktop                                                                                                                               

- context:                                                                                                                                           

    cluster: kuar-cluster                                                                                                                            

    user: clusterUser_kuar_kuar-cluster                                                                                                              

  name: kuar-cluster                                                                                                                                 

- context:                                                                                                                                           

    cluster: minikube                                                                                                                                

    user: minikube                                                                                                                                   

  name: minikube                                                                                                                                     

- context:                                                                                                                                           

    cluster: myAKSCluster                                                                                                                            

    user: clusterUser_myResourceGroup_myAKSCluster                                                                                                   

  name: myAKSCluster                                                                                                                                 

current-context: myAKSCluster                                                                                                                        

kind: Config                                                                                                                                         

preferences: {}                                                                                                                                      

users:                                                                                                                                               

- name: clusterUser_aks-rg_aks-cluster                                                                                                               

  user:                                                                                                                                              

    client-certificate-data: REDACTED                                                                                                                

    client-key-data: REDACTED                                                                                                                        

    token: e4d785d3065d5697f03ac404ac27460f68b973b7185ea4697679077e39ff106437d3a7fe9c79f3be5cc84bbab6728e2d71bc010d0a6c6628bf05162958c122bb          

- name: clusterUser_kuar_kuar-cluster                                                                                                                

  user:                                                                                                                                              

    client-certificate-data: REDACTED                                                                                                                

    client-key-data: REDACTED                                                                                                                        

    token: afc713faf0d9c13f494711c3ab569d52c48c4ac1bef72f53329ab832247c0180f87a167d59c1a784ea0951bd11f043e8eb8aa6089caec2d9d71f61ea58d29b48          

- name: clusterUser_myResourceGroup_myAKSCluster                                                                                                     

  user:                                                                                                                                              

    client-certificate-data: REDACTED                                                                                                                

    client-key-data: REDACTED                                                                                                                        

    token: 2906f9edf219806a855010df4aa104f25eceea94ce748cf1b7813f3af93c531a60b853654b6bc0b24c448491ab3a5896ad36e0fa00d898507c44db7c69f8b283          

- name: docker-desktop                                                                                                                               

  user:                                                                                                                                              

    client-certificate-data: REDACTED                                                                                                                

    client-key-data: REDACTED                                                                                                                        

- name: minikube                                                                                                                                     

  user:                                                                                                                                              

    client-certificate: C:\Users\admin\.minikube\profiles\minikube\client.crt                                                                        

    client-key: C:\Users\admin\.minikube\profiles\minikube\client.key        


we can see that the current-context is myAKSCluster, which is Azure Kubernetes Service. the error is sterm from that either authoriation token had been expired or the  service instance had been removed from azure

Since we already know the root cause of the issue, we can change the kubectl context to the new AKS or the local docker-desktop.

we can follow the steps below 

#to get all the context available in the kubectl configuration file

kubectl config get-contexts

CURRENT   NAME             CLUSTER          AUTHINFO                                   NAMESPACE

          aks-cluster      aks-cluster      clusterUser_aks-rg_aks-cluster

          docker-desktop   docker-desktop   docker-desktop

          kuar-cluster     kuar-cluster     clusterUser_kuar_kuar-cluster

          minikube         minikube         minikube

*         myAKSCluster     myAKSCluster     clusterUser_myResourceGroup_myAKSCluster

#update the current context with local docker-desktop

kubectl config use-context docker-desktop

                                                                  


Monday, September 6, 2021

how to add a list of empty folders to github in windows environment?

When we setup the project structure in the development. the Github have prevent us to push all empty folder to the GitHub Repository in remote server. we can use gitkeep utility in the Macs and Linux environmen to create gitkeep for those blank folder. we cannot gitkeep in the Windows environment. but there is a work around. we can use the powershell scripts to loop through all subfolders under the current project folder and add .gitkeep file in each empty folder. then we can upload those folders to the server.

here is the code to be execute in the windows PowerShell ISE, you should copy it to your windows PowerSehll ISE and replace {Your Current Project Folder path} with your own folder path

Get-ChildItem '{Your Current Project Folder path}' -Recurse -Directory | 

Where-Object {[System.IO.Directory]::GetFileSystemEntries($_.FullName).Count -eq 0} | 

ForEach-Object { New-Item ($_.FullName + "\.gitkeep") -ItemType file}




Tuesday, August 31, 2021

how to fix the cookie is not saving in the browser storage when login mutation is called in GraphQL playground?

 when I implemented the login function, I use the express-session to handle the refresh token. one copy will be save to MongoDB, another one will be save to the cookie. However, I tested the login mutation in the Apollo GraphQL playground. the cookie had been sent in the response header, but it never save in the browser.

the root cause of this issue is sterm from the playground setting.

by default "request.credentials": "omit",  it should be "request.credentials": "include", to force the playground to save the cookie

here is the original setting of playground

{

  "editor.cursorShape": "line",

  "editor.fontFamily": "'Source Code Pro', 'Consolas', 'Inconsolata', 'Droid Sans Mono', 'Monaco', monospace",

  "editor.fontSize": 14,

  "editor.reuseHeaders": true,

  "editor.theme": "dark",

  "general.betaUpdates": false,

  "prettier.printWidth": 80,

  "prettier.tabWidth": 2,

  "prettier.useTabs": false,

  "request.credentials": "omit",

  "schema.disableComments": true,

  "schema.polling.enable": true,

  "schema.polling.endpointFilter": "*localhost*",

  "schema.polling.interval": 2000,

  "tracing.hideTracingResponse": true,

  "queryPlan.hideQueryPlanResponse": true

}

the following is the updated configuration


{

  "editor.cursorShape": "line",

  "editor.fontFamily": "'Source Code Pro', 'Consolas', 'Inconsolata', 'Droid Sans Mono', 'Monaco', monospace",

  "editor.fontSize": 14,

  "editor.reuseHeaders": true,

  "editor.theme": "dark",

  "general.betaUpdates": false,

  "prettier.printWidth": 80,

  "prettier.tabWidth": 2,

  "prettier.useTabs": false,

  "request.credentials": "include",

  "schema.disableComments": true,

  "schema.polling.enable": true,

  "schema.polling.endpointFilter": "*localhost*",

  "schema.polling.interval": 2000,

  "tracing.hideTracingResponse": true,

  "queryPlan.hideQueryPlanResponse": true

}

Tuesday, August 24, 2021

how to use Powershell to convert CSV file into Json format data?

 there is a built-in function in powershell cmdlet, which will allow us to convert the csv data into json format data.

first we should go to the folder where is the csv file stored. my csv file is found in this folder

C:\code\django\django-search-app\fixtures

PS C:\code\django\django-search-app\fixtures> ls

    Directory: C:\code\django\django-search-app\fixtures

Mode                 LastWriteTime         Length Name

----                 -------------         ------ ----

-a----         8/24/2021   1:26 PM         872488 books.csv

-a----         8/24/2021   1:35 PM         883612 books_title_author.csv


here is script to be run the in windows powershell and it should be executed inside the  folder

PS C:\code\django\django-search-app\fixtures> $topicsjson = import-csv .\books_title_author.csv | ConvertTo-Json

PS C:\code\django\django-search-app\fixtures> $topicsjson | Add-Content -Path "myData.json"

 $topicsjson = import-csv .\books_title_author.csv | ConvertTo-Json

 $topicsjson | Add-Content -Path "myData.json"

after the scripts is executed.

there should be a json file name myData.json within the file.

PS C:\code\django\django-search-app\fixtures> ls

    Directory: C:\code\django\django-search-app\fixtures

Mode                 LastWriteTime         Length Name

----                 -------------         ------ ----

-a----         8/24/2021   1:26 PM         872488 books.csv

-a----         8/24/2021   1:35 PM         883612 books_title_author.csv

-a----         8/24/2021   1:40 PM        2047343 myData.json





Monday, August 23, 2021

how to use timer to debug the performance issue in python?

 it is very common to encounter the performance issue. it is very easy to identfiy the function with such issue by adding the timer inside the function or put the timer before and after the function call.

here is a sample snippet to show how to use the time to track the function execution

import time

# @cache
def fib(n):
    if n<=1:
        return n
    else:
        return fib(n-1) +fib(n-2)

def main():
    start=time.perf_counter()
    for i in range(40):
        print(ifib(i))
    print("done")
    elapsed= time.perf_counter() -start
    print(f"completed in {elapsed} seconds")
        

if __name__ == '__main__':
    main()

the output is showing that the function was completed in 69.8057579 seconds.  it indicated that we should opitmize this function for better performance.


PS C:\code\python\python> & C:/Python39/python.exe c:/code/python/python/tutorial/cache/fibonacci_sequnce.py

0 0

1 1

2 1

3 2

4 3

5 5

6 8

7 13

8 21

9 34

10 55

11 89

12 144

13 233

14 377

15 610

16 987

17 1597

18 2584

19 4181

20 6765

21 10946

22 17711

23 28657

24 46368

25 75025

26 121393

27 196418

28 317811

29 514229

30 832040

31 1346269

32 2178309

33 3524578

34 5702887

35 9227465

36 14930352

37 24157817

38 39088169

39 63245986

done

completed in 69.8057579 seconds

PS C:\code\python\python>

how can we improve the performance of this function? Cache will dramatically improve the execution time.

here is the improved version 

from functools import cache
import time

@cache
def fib(n):
    if n<=1:
        return n
    else:
        return fib(n-1) +fib(n-2)

def main():
    start=time.perf_counter()
    for i in range(40):
        print(ifib(i))
    print("done")
    elapsed= time.perf_counter() -start
    print(f"completed in {elapsed} seconds")
        

if __name__ == '__main__':
    main()

done

completed in 0.0112849 seconds

the execution time is less than 1 seocond which is huge change comparing to the previous function will cost 89 second to complete.







Saturday, August 21, 2021

MVC(Model View Controller) Design Pattern in few words

we can use one sentence to describe each component in MVC model. 

M: Model manage business logic and data

V: View manage the display of data

C: Controller handle page event and navigation between pages

Friday, August 6, 2021

how to open a pdf file in chrome instead of download it?

 It is pretty straightforward to set the chrome to open the file instead of download it within the chrome setting.

here is the path the setting

chrome://settings/content/pdfDocuments

open the chrome and paste the above in the address bar. then select Open PDFs in Chrome





Tuesday, August 3, 2021

Visual Studio Code Settings for fullstack devleopment

 here are some of settings from my own personal favoriate


  //custom settings
    "editor.mouseWheelZoom": true,
    "workbench.activityBar.visible": true,
    "workbench.editor.showTabs": false,
    "workbench.sideBar.locataion": "right",
    "editor.minimap.enabled": false,
    "zenMode.centerLayout": true,
    "workbench.iconTheme": "vscode-great-icons",
    "workbench.sideBar.location": "right"

Saturday, July 31, 2021

great repository for Tailwind css and Django

I am a big fan of Tailwind CSS. It is a great companion of Styled Component.

you should be able to find lots of useful resource for Tailwind CSS in this GitHub

https://github.com/aniftyco/awesome-tailwindcss


Tailblocks Ready to use Tailwind CSS Block

It is a great place to find the suitable CSS block to copy and paste in your project

https://tailblocks.cc/


a site with all Django package

https://djangopackages.org/


Save All Resources

https://chrome.google.com/webstore/detail/save-all-resources/abpdnfjocnmdomablahdcfnoggeeiedb/related?hl=en


Virtual Environment for django and python development

https://virtualenvwrapper.readthedocs.io/en/latest/


how to move the side bar to the right in visual studio code?

 I had work for Visual Studio since 2003 version. it is default by the side bar and explorer are located in the right hand side. However the side bar is shown in the left hand side of the visual studio code. I am really not used to be with the change of the location.

it is very easy to switch it to the one which is the right hand side. just right click  to the side bar, then select Move Side Bar Right menu item from the Menu.













Now it is back to the layout that I work most of the time.




how to setup template folder for Django development?

 there are two ways to setup the template folder for django development.

first we can setup the path that Django framework can automatically recognize it..

under the component folder, we have to create the a template folder, then create a folder with name matching the component name.

for example we have a lead component, then the structure of the project should look like as following








in the view.py, we can implement with the code snippet below

from django.shortcuts import render

# Create your views here.

def home_page(request):
    return render(request"leads/home_page.html")

second. we can modify the DIRS attribute in  TEMPLATES setting section in the settings.json to map to the templates path.

TEMPLATES = [
    {
        'BACKEND''django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS'True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

then we only have to create a templates folder under the current component folder. we can add the template html in the template folder.







in the view.py we use the template page directly.

def home_page(request):
    return render(request"home_page.html")








Friday, July 30, 2021

how to fix "Import "django.contrib.auth" could not be resolved from sourcePylance" in Django application development?

 when I try to import a library to the project. I spot a curly underline for the library that i just imported.

I hovered the mouse to the underneath, the warming message as following

    "Import "django.contrib.auth" could not be resolved from sourcePylance"


the root cause of this issue is related to the VS Code workspace configuration. we have to add this line to get ride of the error message.

{
    "python.pythonPath""/venv/bin/python",
}

Since I did not have the .vscode folder when I setup my django project with command line window.

I have to manually create a .vscode folder under the project and add the settings.json file inside it.

I put the above setting in the settings.json file.  The warming message finally resolved.










update: if the above solution still doesn't work

you can change the python interpreter for the current project by doing the following

  • use Ctrl-Shift-p to open command palette
  • type python interpreter in the command palette
  • select Enter interpreter path
  • find the python.exe file under your venv\scripts folder


How can we set restrictions on page in flask app?

 if we want to the user had to login to view the page.

we can use this decorator   @login_required to enforce only login user can access the page.

@app.route('/private')
@login_required
def private_page():
purchase_form = PurchaseItemForm()
if request.method == "POST":
purchased_item = request.form.get('purchased_item')
p_item_object = Item.query.filter_by(name=purchased_item).first()
if p_item_object:
if current_user.can_purchase(p_item_object):
p_item_object.buy(current_user)
flash(f"Congratulations! You purchased {p_item_object.name} for {p_item_object.price}$", category='success')
else:
flash(f"Unfortunately, you don't have enough money to purchase {p_item_object.name}!", category='danger')
return redirect(url_for('private_page'))
if request.method == "GET":
items = Item.query.filter_by(owner=None)
for item in items:
print(item.name)
return render_template('market.html', items=items, purchase_form=purchase_form)

Monday, July 26, 2021

how to implement dynamic routing in Flask

 When we want to pass into a variable on routing. we can use the following code to pass the variable <routeVariable> in the route path.

@app.route("/mypage/<username>"

def  my_page(username):

        return f"<h1>Hello {username}'s page<h1>"


the output is 

hello dan's page

how to force a flask web app to run on specific port in local development?

 when I execute flask run to launch the flask web app in my laptop. I usaully encoutered an error as following.

    "OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions " 

since the windows firewall had block this port.

I can assign the port during the launch to void this issue. i assing 300 for this app.

flask run -h localhost -p 3000 

Saturday, July 24, 2021

Python Quick Reference

It is a quick reference for seasoned developer, who already master at least one programming language. for myself, I have worked with C# for more than 10+ years. this reference can help you easily translate from other language to python

Naming Variables : camel Case

    myVariable

Data Types: 

    Text Type: 

         str "hello world"

    Numeric Types: 

        int : (10),

        long :(101L)

        float: (10.01), 

        complex: (3j)

    Sequence Types:

        list: ["a","b","c","d"], 

        tuple: immutable 

        myTuple = ("a","b","c","d")  

       tuple[0]="New assignment"  TypeError: 'tuple' object does not support item assignment

        range: generate a sequence of integer

        range(5) : 0 1 2 3 4

        range(0, 5, 2) : 0 2 4

    Mapping Type: 

        dictionary: list of key value pairs

        myDictionary={"key1:value1, "key2:value2 }

    Set Types:

    set 

    frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

Comments

    # single comment

    """

    multiple line comments

    another line comments

    """

Strings

Multiline and Formatting Strings

Indentation

Arithmetic Operators

Comparison Operators

    <, >, <=, >=, ==, !=, <>

Logical Operators

    and, or, not

Assignment Operators

    a=b assign value from right to left

    a +=b a=a+b

    a -=b a=a-b

   a *=b a=a*b

    a /=b a=a/b

    a **=b a=a**b

    a //=b   a=a//b   10 //=3   => 10//3=3

 If Statements

    if condition:

    elif condition:

    else:

Ternary If Statements

    message= "true condition" if condition else "false condition"

Lists

    operators:

        Length: len([1, 2, 3] => 3

        Concatenation: ["a", "b", "c"] + [1, 2, 3]  => ["a", "b", "c", 1, 2, 3]

        Repetition: [a, b] * 3 => ["a", "b", "a", "b", "a", "b"]

        Slicing [1: ]   myList=[1,  2,  3] myList[1:] => [2, 3]

        Indexing :

        myList=[1,  2,  3]  

        offsets starting from zero:  myList[1] => 2

         if negative counting from the right side:  myList[-1] => 3

      Built in List methods 

          max(myList) =>3

          min(myList) => 1

         list: convert  iterable object into a list

         list("abcd")=>[a, b, c, d]

         list(123456) TypeError: 'int' object is not iterable

         list("123456") => [1, 2, 3, 4, 5 ,6]

         list({12, "ab", [1, 3]}) => [12, "ab", [1, 3]]

Useful List Methods

  • append : add item the end of the list
  • count: find the number of occurrence of object
  • extend: append iterable object to the list
  • insert: add item to the offset index
  • pop: return the item from the list
  • remove: remove item from the list
  • reverse: reverse the order of items in the list
  • sort: sort items in the list

Deleting Items from Lists

    del list(obj) exactly like list.remove(obj)

Sets

    not allow to have duplicate item

Set Union Intersection & Difference

    union : setA | setB

    intersect: setA & setB

    differece: setA - setB

    symmetric_difference: setA ^ setB

Dictionaries

    key value pairs data structure

   myDict ={

        "key1" : value1, 

        "key2" : value2,

        "key3" : value3

}

value1=myDict["key1"]

    Functions:

        len:

        

    Methods:

For Loops

    for item in list or set:

        print(item)

Loop Through Dictionaries

    for key in dict: 

        print(f"key: {key} value: {dict[key]}")

While Loop

    number=0

    while number < 3

         number +=1

Break and Continue

    break: exist the the loop if condition meets

              number=0

                while number < 3

                     if number==2

                        break;

                     number +=1

    continue: continue the loop if the condition is true

                       number=0

                            while number < 3

                     if number <=2

                            continue;

                            number +=1

Functions 

    def myfunction():

        print("this  is my first function")

Built in Functions and Import Statement

    import python module

        import math

    import specific method from the module

        from math import floor

Creating Modules

        create a python file myModule.py

        in another file use import myModule to reference the moudule

         printing all variables and function names of the "myModule" module

          dir(myModule)

Classes and Objects

    classes are the blueprints of objects

    objects are the instances of classes

Creating Classes and Objects

     class person

        #define the constructor

        def __init__(self, firstName,lastName):

                self.fistName=firstName

                self.lastName=lastName 

     myObject=person("first name", "last name")

 Inheritance

    class driver(person)  #driver is inherited from person

Printing Objects

    # override method

    def __str__(self) -> str:

           return f"last name: {self.firstName}, last name: {self.lastName}"

Working With Dates

    from datetime import datetime #work with datetime

    from datetime import date    #work with actual date

Formatting Dates

    now=datetime.now()

    now.strftime("datetime string formatter") 

Creating Files

    file =open("./myfile.txt", "w")      # create a text file myfile.txt in the current working dir

    flags: a -> append

              r -> read

              r+ -> read and write

              w -> write

    file.close() # to properly close the file being read or write    

Reading From Files

     file =open("./myfile.txt", "r") 

     file.read()

     file.close()

A Better Way To Work With Files

    import os.path

    if(os.path.isfile(myfile.txt):  #ensure the file exists before read write operations

            with open("./myfile.txt", "r")  as file

                file.read()

Fetching Data From Internet

     import json

    from urllib import request

    response = request.urlopen(("https://fakerapi.it/api/v1/companies?_quantity=5"))

    resjson = json.loads(response.read())

    print(resjson["data"])

Pip & Modules

    pip3: python package manager

    pip3 install requests

 Request Module

    import json

    import requests

    response = requests.get(("https://fakerapi.it/api/v1/companies?_quantity=5"))

    print(response.text)

    jsonData = json.loads(response.text)

    print(jsonData["data"])

Text To Speech

  pip3 install pyttsx3

   import pyttsx3

   pyttsx3.speak


Asterik * 

 * is argument-unpacking and ** keyword-argument-unpacking operators

The single star * unpacks the sequence/collection into positional arguments

The double start ** uses a dictionary and thus named arguments.