Computer

Programming

For Beginners

Quick Start Guide

Tutorial Book 3

Ray Yao

Copyright © 2015 by Ray Yao

All Rights Reserved

Neither part of this book nor whole of this book may be reproduced or transmitted in any form or by any means electronic, photographic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without prior written permission from the author. All rights reserved!

Ray Yao

About the Author:  Ray Yao

Certified PHP engineer by Zend, USA

Certified JAVA programmer by Sun, USA

Certified SCWCD developer by Oracle, USA

Certified A+ professional by CompTIA, USA

Certified ASP. NET expert by Microsoft, USA

Certified MCP professional by Microsoft, USA

Certified TECHNOLOGY specialist by Microsoft, USA

Certified NETWORK+ professional by CompTIA, USA

www . amazon . com/author/ray-yao

“In 8 Hours” eBooks & Books on Amazon

Advanced C++ in 8 Hours

Advanced Java in 8 Hours

AngularJs in 8 Hours

C# in 8 Hours

C# Q & A

C++ in 8 Hours

C++ Q & A

Django in 8 Hours

Go in 8 Hours

Html Css in 8 Hours

Html Css Q & A

Java in 8 Hours

Java Q & A

JavaScript in 8 Hours

JavaScript Q & A

JQuery in 8 Hours

JQuery Q & A

Kotlin in 8 Hours

Linux Command Line

Linux Q & A

MySql in 8 Hours

Node . Js in 8 Hours

Perl in 8 Hours

Php MySql in 8 Hours

Php Q & A

PowerShell in 8 Hours

Python in 8 Hours

Python Q & A

R in 8 Hours

Ruby in 8 Hours

Rust in 8 Hours

Scala in 8 Hours

Shell Scripting in 8 Hours

Swift in 8 Hours

Visual Basic in 8 Hours

Visual Basic Q & A

Xml Json in 8 Hours

Preface

“Computer Programming” covers all essential computer language knowledge. You can learn complete primary skills of computer programming fast and easily.

The book includes six crash courses, such as PowerShell, Node.js, Django, Scala, Swift, Perl.

Note:

This book is only for computer programming beginners, it is not suitable for experienced computer programmers.

Source Code for Download

This book provides source code for download; you can download the source code for better study, or copy the source code to your favorite editor to test the programs.

Table of Contents

PowerShell

Hour 1     Introduction

Hour 2     Basics

Hour 3     Operators

Hour 4     Statement

Hour 5     Function

Hour 6     String

Hour 7     Object

Hour 8     Pipeline

Appendix 1

Appendix 2

Source Code Download

Node.Js

Hour 1     Introduction

Hour 2     Basics

Hour 3     Event

Hour 4     Write/Read

Hour 5     Stream

Hour 6     File

Hour 7     Operations

Hour 8     Modules

Appendix

Source Code Download

Django

Hour 1     Introduction

Hour 2     Basics

Hour 3     Django Tags

Hour 4     Models

Hour 5     Form/Method

Hour 6     Administration Tool

Appendix 1

Python Basic

Appendix 2

Texts & Answers

Source Code Download

Scala

Hour 1     Introduction

Hour 2     Basics

Hour 3     Operators

Hour 4     Statement

Hour 5     Methods

Hour 6     Arrays

Hour 7     Collection

Hour 8     Class/Object

Appendix 1

Appendix 2

Source Code Download

Swift

Hour 1     Introduction

Hour 2     Basics

Hour 3     Operators

Hour 4     Statements

Hour 5     String/Array

Hour 6     Collection

Hour 7     Class/Object

Hour 8     Operations

Q & A

Source Code Download

Perl

Hour 1     Introduction

Hour 2     Basics

Hour 3     Hash

Hour 4     Statement

Hour 5     Operations

Hour 6     Files

Hour 7     Functions

Hour 8     Class/Object

Appendix

Perl Q & A

Source Code Download

Source Code Download

PowerShell

Hour 1

Introduction

What is PowerShell?

PowerShell is a command-line script environment running on a Windows machine for automate system and application management. You can think of it as an extension of the command line prompt cmd. exe. PowerShell is built on the. net platform, and all that are passed by the command are . net objects. PowerShell fully supports the use of objects. It is readable, easy to use, and powerful. From Window 7 to now, various operating systems have built-in PowerShell platforms.

Currently there are five versions of PowerShell:

Operating Systems

Versions:

Windows Vista or Windows  Server 2008

PowerShell  1 . 0

Windows 7 or Windows Server 2008 R2

PowerShell  2 . 0

Windows 8 or Windows Server 2012

PowerShell  3 . 0

Windows 8 . 1 or Windows Server 2012 R2

PowerShell  4 . 0

Windows 10 or Windows Server 2016

PowerShell  5 . 0

On August 18, 2016, Microsoft announced that the open source, cross-platform version of PowerShell will support multiple operating systems including Windows, MacOS, CentOS and Ubuntu. It is called “PowerShell Core” and runs on . net Core.

Start PowerShell

Method 1:

Click Start > Windows PowerShell

Method 2:

Click Start > Type “PowerShell” in the Search field.

Method 3:

Click Start > Type “PowerShell” in the Run field.

Method 4:

Click Start > All Programs > Accessories > Windows PowerShell.

After you start the PowerShell, you can see a blue screen.

PowerShell Commands

The format of Powershell command is “verb - noun”.

The syntax to check the PowerShell commands is as follows:

Get-Command

Example 1.1

PS C:\Users\RAY> Get-Command

CommandType     Name

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

Alias           Add-ProvisionedAppxPackage

Alias           Apply-WindowsUnattend

……

Explanation:

CommandType: There are three command types in PowerShell:

1. Alias: another name of the command.

2. Function: the command is used for a function.

3. Comlet: a powerful PowerShell command, its parameter is a . net object.

Note:

1 . For easier reading, we will omit “PS C:\Users\RAY> ” in later pages .

2 . The PowerSell commands will be shown in bold type in later pages .

Get Command Alias

The syntax to get the command alias is as follows:

Get-Command -CommandType Alias

Example 1.2

Get-Command -CommandType Alias

CommandType     Name

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

Alias           % -> ForEach-Object

Alias           ? -> Where-Object

Alias           ac -> Add-Content

…..

Explanation:

The alias of the “ForEach-Object” is %.

The alias of the “Where-Object” is ?

The alias of the “Add-Content” is ac

By the way, the alias of the “Get-Command” is gcm.

Note:

1 . For easier reading, we will omit “PS C:\Users\RAY> ” in later pages .

2 . The PowerSell commands will be shown in bold type in later pages .

Get Commands with Verb

The syntax to get some commands with the specified verb is as follows:

Get-Command –verb Specified-Verb

Example 1.3

Get-Command -verb Clear

CommandType     Name

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

Function        Clear-BitLockerAutoUnlock

Function        Clear-Disk

Function        Clear-DnsClientCache

Function        Clear-FileStorageTier

Function        Clear-Host

Function        Clear-StorageDiagnosticInfo

Cmdlet          Clear-Content

Cmdlet          Clear-EventLog

Cmdlet          Clear-History

……

Explanation:      “Get-Command -verb Clear” gets the commands with “Clear” verb.

Get Commands with Noun

The syntax to get some commands with specified noun is as follows:

Get-Command  -noun Specified-Noun

Example 1.4

Get-Command -noun Service

CommandType     Name

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

Cmdlet          Get-Service

Cmdlet          New-Service

Cmdlet          Restart-Service

Cmdlet          Resume-Service

Cmdlet          Set-Service

Cmdlet          Start-Service

Cmdlet          Stop-Service

Cmdlet          Suspend-Service

……

Explanation:

“Get-Command -noun Service” gets the commands with “Service” noun.

Command with * Character

The syntax to use * character in the command is as follows:

Get-Command  verb-*

Get-Command  *-noun

Example 1.5

Get-Command Set-*

CommandType     Name

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

Function        Set-ClusteredScheduledTask

Function        Set-DAClientExperienceConfiguration

Function        Set-DAEntryPointTableItem

……

“Get-Command Set-*” returns all commands beginning with “Set”

Example 1.6

Get-Command *-Service

CommandType     Name

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

Cmdlet          Get-Service

Cmdlet          New-Service

Cmdlet          Restart-Service

……

“Get-Command *-Service” retunrs all commands ending with “Service ” .

Help Command

The syntax to get help for a command is as follows:

Help Specified_Command

Example 1.7

Help Clear-Host

NAME

Clear-Host

SYNOPSIS

SYNTAX

Clear-Host [<CommonParameters>]

DESCRIPTION

RELATED LINKS

http://go. microsoft. com/fwlink/?LinkID=225747

REMARKS

To see the examples, type: "get-help Clear-Host -examples".

For more information, type: "get-help Clear-Host -detailed".

For technical information, type: "get-help Clear-Host -full".

For online help, type: "get-help Clear-Host -online"

……

Explanation:      “Help Clear-Host” can help to know more about the “Clear-Host” command in detail.

Man Command

Man is an alias of the Help commands.

The syntax to man a command is as follows:

Man Specified_Command

Example 1.8

Man Start-Process

NAME

Start-Process

SYNTAX

Start-Process [-FilePath] <string> [[-Argum

ring>] [-LoadUserProfile] [-NoNewWindow] [-

ing>] [-RedirectStandardOutput <string>] [-

Maximized}] [-UseNewEnvironment]  [<CommonP

Start-Process [-FilePath] <string> [[-Argum

ring>] [-Wait] [-WindowStyle <ProcessWindow

ALIASES

saps

start

……

Explanation:

“Man” can know more about the “Man” command in detail.

Get Service

“Get-Service” command can know about the service the computer provides.

Get-Service

Example 1.9

Get-Service

Status   Name               DisplayName

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

Stopped  AeLookupSvc        Application Experience

Stopped  ALG                Application Layer Gateway Service

Running  AlibabaProtect     Alibaba PC Safe Service

Stopped  AppIDSvc           Application Identity

Running  Appinfo            Application Information

Stopped  AppReadiness       App Readiness

Running  Audiosrv           Windows Audio

Stopped  AxInstSV           ActiveX Installer (AxInstSV)

Stopped  BaiduUpdater       Baidu Updater

Stopped  BDESVC             BitLocker Drive Encryption Service

Running  BFE                Base Filtering Engine

Running  BITS               Background Intelligent Transfer Ser...

Running  Browser            Computer Browser

……

Explanation:

“Get-Service” can view the service in the current computer.

Arithmetical Operation

We can think of PowerShell as a calculator, input some numbers, add, subtract, multiply, divide and mod, then press Enter key, and see the result.

Example 1.10

10 + 20 + 30

60

100 - 20

80

2 * 80

160

90 / 2

45

10 % 3

1

Explanation:

“+ , - , * , / , % ” are the arithmetical operators. After you press the Enter key, you can see the result.

Execute external commands

PowerShell can run external commands as follows:

External Commands

Usages

ipconfig

Check network configuration

netstat

Check network port status

route print

Check route information

cmd

Launch the CMD console

cmd /c help

Check available CMD commands

exit

Exit the CMD

Example 1.11

cmd /c help

For more information on a specific command, type HELP command-name

ASSOC          Displays or modifies file extension associations.

ATTRIB         Displays or changes file attributes.

BREAK          Sets or clears extended CTRL+C checking.

……

Explanation:

“cmd /c help” can check the available CMD commands.

Create a PowerShell File

PowerShell has own its scripting file, its extension name is .psl

The syntax to create a PowerShell file is as follows:

echo “ file contents ” > name    . psl

Example 1.12

echo "This is a PowerShell scripting file" > myfile.ps1

Explanation:

After input the above command, please press the Enter key.

“echo “ file contents ” > name. psl” creates a PowerShell file.

“This is a PowerShell scripting file” is the content of this PowerShell file.

“myfile. psl” is the file name of this PowerShell file.

View the PowerShell File

We can view the contents of the specified PowerShell file.

The syntax to view the contents of the PowerShell file is as follows:

Get-Content     . / myfile. ps1

Example 1.13

echo "This is a PowerShell scripting file" > myfile.ps1

Get-Content ./myfile.psl

This is a PowerShell scripting file

Explanation:

“Get-Content . /myfile. psl” can show the content of the myfile. psl.

The output is “This is a PowerShell scripting file”.

“./ ” means the relative path.

Hour 2

Basics

Comment

PowerShell uses the # symbol as the comment mark. The PowerShell compiler will ignore the contents of the comments.

# comment

Example 2.1

100 + 200    # add

300

100 - 30      # subtract

70

2 * 500        # multiply

1000

27 / 3           # divide

9

8 % 2           # mod

0

Explanation:

“#add, #subtract, #multiply, #divide, #mod” are PowerShell comments, which are ignored by the PowerShell compiler.

Variable

Variables are used to hold data temporarily.

Define a variable:

$variable_name = value

Show the value of a variable:

$variable_name

Example 2.2

$x = 100    # define a variable

$y = 200    # define a variable

$z = 300    # define a variable

$x         # show $x value

100

$y         # show $y value

200

$z         # show $z value

300

Variable Name

In PowerShell, variable names start with the dollar sign $, and the remaining characters can be any alphanumer, underscore, and any letter.

PowerShell variable names are case-insensitive ($var and $VAR are the same variable). Some special characters are generally not recommended to work as variable names.

The following example will show the usages of some variables:

Example 2.3

$result=$a=$b=$c=100    # assign a value

$result     # show the value

100

Example 2.4

$x=111

$y=222

$x,$y=$y,$x      # exchange the values

$x

222

$y

111

Data Type

Any data has its own data type, we can use “gettype(). name” to check the data type of a variable value.

(data)    . gettype(). name

Example 2.5

(100).gettype().name

Int32

(8888888888888888).gettype().name

Int64

(168.88).gettype().name

Double

("Go in 8 Hours").gettype().name

String

(Get-Date).gettype().name

DateTime

Explanation:

“(data). gettype(). name” can get the data type of various data.

Specify Data Type

We can specify a data type for a variable when defining a variable.

[type] $variable = value

Example 2.6

[int]$a=100.88

$a

101

[string]$b=200.99

$b.gettype().name

String

Explanation:

“[int]$a=100. 88” specifies an “int” type for the $a.

“[string]$b=200. 99” specifies a “string” type for the $b.

Date Time Type

To define a variable with Date Time type is as follows:

[Date Time] $variable = value

Example 2.7

[DateTime] $day=Get-Date

$day

7/4/2019 17:41:28

$day.DayOfWeek

Thursday

$day.DayOfYear

185

Explanation:

“[DateTime] $day” specifies Data Time type for the $day.

“Get-Date” gets the current date.

“$day. DayOfWeek” gets the current day in the week.

“$day. DayOfYear” gets the numbers of days in the year.

Create an Array

An array is a collection of variables with the same type and name.  These variables are called elements of an array, and each element has a number called an index, also called key.

The syntax to create an array is as follows:

$array_name = element0, element1, element2, element3,    …

Example 2.8

$myArray=100, 111, 112, 113

$myArray

100

111

112

113

Explanation:

“$myArray=100, 111, 112, 113” creates an array with four elements. Their values are 100, 111, 112, 113.

The index of the first element is 0.

The index of the second element is 1.

The index of the third element is 2.

Polymorphic Array

The elements of the PowerShell array can be polymorphic, such as int type, string type, date time type, or empty element.

(1) Create a different type array:

$array_name = int, “String”, (date type),     …

Example 2.9

$myArray = 10, “Good”, (get-date)

$myArray       # different type array

10

Good

7/4/2019 20:18:30

(2) Create an empty array:

$array_name = @()

Example 2.10

$myArray = @()      # empty array

$myArray -is[array]    # check if it’s a array

True

Access Array

The elements of an array can be indexed, with the first element having an index of 0 , and the last element having an index of -1.

The syntax to access the array is as follows:

$array_name[ index ]

Example 2.11

$myArray=@()

$myArray -is[array]

True

$myArray = "C#","in","8", "Hours"

$myArray[0]

C#

$myArray[1]

in

$myArray[2]

8

$myArray[-1]

Hours

Explanation:

“$myArray[0]” accesses the first element “C#”.

“$myArray[-1]” accesses the last element “Hours”.

Array Element

(1) We can create an array by range.

$array_name = num1     .. num2

Example 2.12

$myArray = 100 .. 102   # 10 0 . . 102 is a range

$myArray

100

101

102

(2) We can append some elements to the array.

$array_name += "new_element"

Example 2.13

$myArray = "C++","in","8 Hours"

$myArray += "is a good book!"   # append

$myArray

C++

in

8 Hours

is a good book    !

Insert, Remove Element

To insert or remove Array elements in PowerShell, we need to convert the Array object to an ArrayList object first. Because ArrayList objects have Insert() and RemoveAt() methods, which can insert or delete array elements.

$arraylist = $array   # convert array object to arraylist object

$arraylist. Insert(index, element)   # insert an element

$arraylist    . Remove(index)      # remove an element

Example 2.14

$myArray = 0..8

$arraylist = $myArray     # convert

$arraylist.Insert(6,'100')     # insert

$arraylist.RemoveAt(3)      # remove

$arraylist

0

1

2         # remove an element “3”

4

5

100      # insert 100 before index 6

6

7

8

Clone Array

We can clone a specified array as another array.

The syntax to clone an array is as follows:

$array2 = $array1    . Clone()

Example 2.15

$array1 = "AngularJS", "in", "8", "Hours"

$array2 = $array1.Clone()

$array2

AngularJS

in

8

Hours

Explanation:

“$array2 = $array1.Clone() ” clones an array “array1” as another array “array2“.

Hour 3

Operators

Comparison Operators

PowerShell has following comparison operators:

Operators

Descriptions

-eq

equal

-ne

not equal

-gt

greater

-ge

greater or equal

-lt

less

-le

less or equal

-contains

includes

-noncontains

not includes

Example 3.1

(6,7,8) -contains 3

False

(1,3,6 ) -contains 6

True

(0,2,5 ) -notcontains 4

True

8 -eq 6

False

"C" -eq "c"

True

"R" -ne "r"

False

10 -lt 100

True

100 -ge 100

True

Explanation:

-eq

equal

-ne

not equal

-gt

greater

-ge

greater or equal

-lt

less

-le

less or equal

-contains

includes

-noncontains

not includes

Logical Not

The operator of negation is -not or !

Operator

Descriptions

- not

logical not

!

logical not

Example 3.2

$bool = 200 -gt 100

$bool

True

-not $bool

False

!($bool)

False

Explanation:

If $bool is equal to true, then –not $bool will return false.

If $bool is equal to true, then ! $bool will return false.

Boolean Operators

The following is PowerShell boolean operators:

Operators

Descriptions

-and

and

-or

or

-not

not

Example 3.3

$x = 1     # 1 represents true

$y = 0     # 0 represents false

$x -and $y

False

$x -or $y

True

Explanation:

true -and true;

returns true;

true -and false;

returns false;

false -and false;

returns false;

true or true;

returns true;

true or false;

returns true;

false or false;

return false;

Arithmetic Operators

The following is PowerShell arithmetic operators:

Operators

Descriptions

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulus

Example 3.4

$a = 20

$b = 10

$a + $b        #addition

30

$a - $b         #subtraction

10

$a * $b         #multiplication

200

$a / $b         #division

2

$a % $b       #modulus

0

Assignment Operators

The following is PowerShell assignment operators:

Operators

Meanings

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

Example 3.5

$a = 30

$b = 10

$a += $b

$a

40

$a = 30

$b = 10

$a -= $b

$a

20

$a = 30

$b = 10

$a *= $b

$a

300

$a = 30

$b = 10

$a /= $b

$a

3

$a = 30

$b = 10

$a %= $b

$a

0

Explanation:

a += b means a = a + b

a -= b means a = a - b

a *= b means a = a * b

a /= b means a = a / b

a %= b means a = a % b

Increase / Decrease Operators

The syntax to use ++ or -- is as follows:

Operators

Descriptions

++

Increase 1

--

Decrease 1

Example 3.6

$x = 10

$x++

$x

11

$y = 10

$y--

$y

9

Explanation:

“$x++” makes the value of $x increasing 1.

“$y--” makes the value of $y decreasing 1.

If-elseif-else

The syntax to use the condition statement is as follows:

If( condition ){  # if true, do this

}

elseif( condition ) {  # if true, do this

}

else{  # if not true, do this

}

Example 3.7

$num=10

if ($num -gt 20) {"$num  is greater than 20 " } else {"$num  is less than 20 "}

10  is less than 20

# “num –gt 20” is false, so the output is “10 is less than 20”.

Example 3.8

$n = +1

if($n -lt 0 ){"-1" } elseif($n -gt 0){"+1"}

+1

# “$n –gt 0” is true, so the output is “+1”

Example 3.9

$color = "yellow"

If( $color -eq "green" ){

"The color is green"

}

Elseif( $color -eq "yellow"){

"The color is yellow"

}

Elseif( $color -eq "red" ){

"The color is red"

}

Else{

"The color is white"

}

The color is yellow

Explanation:

The condition is equal to “yellow”, so the output is “The color is yellow”.

Switch Statement

The switch statement is just like a multiple If-elseif-else statement.

switch(<test_value>) {

<condition1> {<action>; break}

<condition2> {<action>; break}

<condition3> {<action>; break}

……

}

The test_value will compare each condition first, if equals one of the “condition” value; it will execute that “action” code. “break;” terminates the code running.

Example 3.10

switch(3){

1 {"One"; break}

2 {"Two"; break}

3 {"Three"; break}

4 {"Four"; break}

}

Three

Explanation:

The test_value is equal to 3, so it outputs “Three”.

Switch statement can be used to compare the strings.

Example 3.11

$book="Ruby"

switch($book){

"Html" {"Html in 8 Hours"; break}

"Ruby" {"Ruby in 8 Hours"; break}

"Java" {"Java in 8 Hours"; break}

"Rust" {"Rust in 8 Hours"; break}

}

Ruby in 8 Hours

Explanation:

The test_value is equal to “Ruby”, so it outputs “Ruby in 8 Hours”

Hour 4

Statement

For Loop

You can use the For loop if you know exactly how many times it will repeat, For loop automatically terminates once it reaches its maximum number.

for (init; condition; repeat){

}

Example 4.1

for ($x = 0; $x -le 4; $x++) {

$x

}

0

1

2

3

4

Explanation:

When $x is less or equal to 4, the For loop will terminate.

The following example shows how to get the sum from 1 to 100.

Example 4.2

$sum=0

for($n=1;$n -le 100;$n++){

$sum+=$n

}

$sum

5050

Explanation:

“for ($n=1;$n -le 100;$n++)” is a For loop statement.

“$n=1” initializes the variable n. The counting begins from 1.

“$n -le 100” is a condition in For loop.

“$n++” increases 1 when repeating one time. “$n” works as both a counter and an increasing value.

Foreach Loop

Foreach loop is used to iterate throughout the each element in a collection .

foreach ($element in $collection) {

}

Example 4.3

$array = ("Java", "Ruby", "Html", "Rust")

foreach ($item in $array) { $item }

Java

Ruby

Html

Rust

Explanation:

“foreach ($item in $array)” iterates throughout the each $item in $array.

$_  Symbol

$_ represents the current element in the current loop.

For example. While iterating throughout the elements in an Array (2, 5, 6, 8), $_  represents 2 in the first loop, $_ represents 5 in the second loop, $_ represents 6 in the third loop, $_ represents 8 in the fourth loop.

Example 4.4

$array = ("Java", "Ruby", "Html", "Rust")

foreach ($_ in $array) { $_ }

Java

Ruby

Html

Rust

Explanation:

In “foreach ($_ in $array)”, $_ represents the current element in this loop.

While Loop

“while loop” loops through a block of code if the specified condition is true.

while ( condition ) {

}

Example 4.5

$array = ("Python", "Django", "Kotlin")

$increase = 0;

while($increase -lt $array.length){

$array[$increase]

$increase += 1

}

Python

Django

Kotlin

Explanation:

“while ($increase -lt $array. length)” loops through the code block while its condition is true.

“$array. length” gets the size of the array.

Do-While Loop

“do... while” loops through a block of code once first, and then repeats the loop if the specified condition is true.

do{

} while ( condition );

Example 4.6

$array = ("C#", "Go", "VB")

$increase = 0;

do {

$array[$increase]

$increase += 1

} while($increase -lt $array.length)

C#

Go

VB

Explanation:

“do... while($increase -lt $array. length)” loops through a block of code once first, and then repeats the loop if the specified condition is true.

Break Statement

“break” keyword is used to stop the running of a loop according to the condition.

break

Example 4.7

$num=0

while ($num -lt 10){

if ($num=5){ break }    # jump out of the while loop

$num++

}

$num     # this command is outside the while loop

5

Explanation:

“if ($num=5){ break }” stops the while loop, executes the next command outside the while loop.

Example 4.8

$num=0

while($num -lt 7)

{   $num++

if($num -eq 5)

{

break    # jump out of the while loop

}

$num     # this command is inside the while loop .

}

1

2

3

4

Explanation:

“if($num -eq 5){break}” stops the while loop, and leaves the while loop.

Continue Statement

“continue” keyword is used to stop the current loop, ignoring the following code, and then continue the next loop.

continue

Example 4.9

$num=0

while($num -lt 5){

$num++

if($num -eq 3){ continue }

else{ $num }

}

1

2

4

5

Explanation:

“if($num -eq 3){ continue }” stops the current loop when $num is 3, and continues the next loop.

Example 4.10

$range = 0..6

foreach ($num in $range){

If($num -eq 4){continue}

$num

}

0

1

2

3

5

6

Explanation:

“If($num -eq 4){continue }” stops the current iteration, and continues to execute the next foreach().

Switch and $_

$_  can be used in Switch statement. $_ represents the current element.

Example 4.11

$nums = 0..5

Switch ($nums){

Default { "The num = $_" }

}

The num = 0

The num = 1

The num = 2

The num = 3

The num = 4

The num = 5

Explanation:

$_ represents the current element in each running.

“Default” will run this command when Switch statement has not specified the related values.

Example 4.12

$nums = 3..8

Switch ($nums){

{($_ % 2) -eq 0} {"$_ is an even number"}

{($_ % 2) -ne 0} {"$_ is an odd number"}

}

3 is an odd number

4 is an even number

5 is an odd number

6 is an even number

7 is an odd number

8 is an even number

Explanation:

$_ represents the current element in each execution.

Hour 5

Function

Function

A function is a code block that can repeat to run many times. To define a function, use “function function_name { }”.

Function function_name($arg) {

}

To call a function, use “function_name;”

function_name

Example 5.1

function myFunction {    # define a function

$num = 100

$num

}

myFunction       # call the function

100

Explanation:

“function myFunction ” defines a function named “myFunction”.

“myFunction” call the function “myFunction”.

Function with Argument

We can call a function with parameters.

function_name   parameters

Example 5.2

function myFunc($arg1, $arg2){

$arg1

$arg2

}

myFunc  Very  Good!      # call the function with parameters

Very

Good    !

Explanation:

“$arg1, $arg2” receives the parameters.

“myFunc  Very  Good! ” calls the function “myFunct”, passes two parameters to “$arg1, $arg2”.

“Very” and  “Good! ” are parameters when calling the function.

Return Values

“return” can return a value to the caller.

function function_name ( $arg ) {  return value  }

To call a function, use “function_name   parameters”

function_name    parameters

Example 5.3

function myFunc($arg1,$arg2){

return $arg1+$arg2        # return the sum to the caller

}

myFunc  Java  Script

JavaScript

Example:

As parameters, “Java” and “Script” are sent to $arg1 and $arg2.

“return $arg1+$arg2” returns the value “JavaScript” to the caller.

Return Value Operation

We can calculate the return values with various ways.

Example 5.4

function Multiply($num){

return $num * $num

}

Multiply 2

$result= Multiply 3

$result++

$result

$result -is [array]

4

10

False

Explanation:

“$result++” increases 1 to the return value.

“$result -is [array]” checks the return value if it is an array.

Default Parameters

We can specify a default parameter value for the function.

function  func_name ($a=v1, $b=v2,…) {

}

Example 5.5

function myFunc($a="Angular", $b="JS") {

return $a + $b

}

myFunc

AngularJS

Explanation:

“myFunc($a="Angular", $b="JS" )” specifies two default parameters for the function “myFunc”

Specify Parameter Type

We can specify the type of the function parameters.

function  func_name( type $arg1, type $arg2,…) {

}

Example 5.6

function myFunc( [int]$x, [int]$y) {

return $x + $y

}

myFunc 10.123   20.5

30

Explanation:

“function myFunc( [int] $x, [int] $y)” specifies the “int” as a parameter type.

“myFunc 10. 123   20. 5” calls the function with two float-type values, but returns an int-type result.

Datatime Parameter

We can specify the Datatime type as the function parameters.

function func_name( [datetime]$arg )

Example 5.7

function DayOfWeek([datetime]$day){

return  $day.DayOfWeek

}

DayOfWeek 1776-7-4

Thursday

DayOfWeek 1949-10-1

Saturday

Explanation:

“DayOfWeek” is a function name.

“[datetime ]$day)” specifies “datetime” as a parameter type.

“DayOfWeek 1776-7-4” calls the function “DayOfWeek” with a datetime-type parameter “1776-7-4”.

“DayOfWeek 1949-10-1” calls the function “DayOfWeek” with a datetime-type parameter “1949-10-1”.

Switch Parameters

A function with the switch parameters will allow user to specify a parameter.

function  func_name([switch] $arg) {

}

Example 5.8

function Hello($name, [switch] $male) {

if ($male) {

"Hello Mr. $name"

} else {

"Hello Ms. $name"

}

}

Hello Andy  -male      # input –male parameter

Hello Rosy  -female       # input –female parameter

Hello Mr. Andy

Hello Ms    . Rosy

Explanation:

“Hello Andy -male” specifies a switch parameter “-male”.

“Hello Rosy -female” specifies a switch parameter “-female”.

Filter Function

Filter function can filter the content by pipeline symbol “|”.

To define a Filter function:

filter func_name(){

}

To call a Filter function:

command     | func_name

Example 5.9

filter myFunc() {     # define a filter

# want to only show the files with extension . exe

if ($_.extension -eq ".exe") { $_ }

}

dir | myFunc     # call the filter function

Output:      # only show the files with extension . exe

Mode                LastWriteTime     Length Name

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

-a---         2019/3/28     10:36     141824 const000. exe

-a---         2019/3/28     11:36     142848 convert000. exe

-a---         2019/3/29     10:16     142336 fun000. exe

Explanation:

“dir | myFunc” calls the filter function, using a “|” pipeline.

Pipeline Function

The pipeline function is a special function that contains three parts, 1. begin.    2. process.    3. end.

Pipeline function is called by the command with “|” symbol.

To define a pipeline function:

function test() {

begin {

}

process {

}

end {

}

}

To call a pipeline function:

command     | pipeline function

Example 5.10

function myFunc() {

begin {

"Start to run"

}

process {

if ($_ -like "a*") { $_ }

# find the elements beginning with "a"

}

end {

"Complete the program"

}

}

$("app", "bee", "ate", "boy", "ago", "bit") | myFunc

Output:

Start to run

app

ate

ago

Complete the program

Explanation:

“if ($_ -like "a*") { $_ }” finds the files beginning with "a".

“ $("app", "bee", "ate", "boy", "ago", "bit") | myFunc ” calls the pipeline function and finds the elements beginning with "a".

Hour 6

String

String

The String is consisted of one or more characters within single quotes or double quotes. The syntax to define a string is:

$myString = ‘ text ’        # using single quotes

$myString = “ text ”           # using double quotes

The string included with the single quotes will return original content.

The string included with the double quotes will return different content.

Example 6.1

$var = 8

$string1 = 'Go in $var Hours'       # single quotes

$string2 = "Go in $var Hours"      # double quotes

$string1

Go in $var Hours

$string2

Go in 8 Hours

Explanation:

'Go in $var Hours' is included by the single quotes, so the string value is an original content.

“Go in $var Hours”' is included by the double quotes, so the string value is a different content.

$_ in the string

When there are $variable in a string, they will be replaced by the value of the variable itself.

If there is $expression in a string, the expression will be executed, they will be replaced by the value of the expression itself.

Example 6.2

"The system directory is located in th e： $env:windir"

# output:

The system directory is located in the： C: \Windows

"The install directory is located in th e： $env:ProgramFiles"

# output:

The install directory is located in the： C: \Program Files

"The name of this machine i s： $env:computername"

# output:

The name of this machine is： RAYYAO

"The current datetime is: $(get-date)"

# output:

The current datetime is    : 07/14/2019 08: 49: 01

Escape Character

The “ ` ” backslash character can be used to escape characters.

`n outputs content to the next new line.

`r makes a return

`t makes a tab

`b makes a backspace

`’ outputs a single quotation mark.

`” outputs a double quotation mark    .

Example 6.3

"She said `"JQuery in 8 Hours`""

She said "JQuery in 8 Hours"    # you can see the “ “

"He said `n Ruby in 8 hours"   # output in different lines

He said

Ruby in 8 hours

Explanation:

`" JQuery in 8 Hours`" escapes the double quotation marks.

“`n Ruby in 8 hours” output this text in the next line.

Multi-Line String

The @” text “@ format can define multi-line String

@”

text1

text2

text3

……

“@

Example 6.4

@”

Go in 8 Hours

Ruby in 8 Hours

Scala in 8 Hours

AngularJS in 8 Hours

JavaScript in 8 Hours

“@

# Output a multi-line string

Go in 8 Hours

Ruby in 8 Hours

Scala in 8 Hours

AngularJS in 8 Hours

JavaScript in 8 Hours

User Interaction

"read-host" is used to accept the input from users

$variable = read-host " prompt "

Example 6.5

$title = read-host "Please input the book title"

# assumes you will input ‘R in 8 Hours’ .

Please input the book title:     R in 8 Hours

The inputted value will be stored in $title.

Example 6.6

"The book title is: $title"

The book title is: R in 8 Hours

Explanation:

$title = read-host "Please input the book title" will accept the input from users, the inputted values will be stored in $title.

"The book title is: $title" shows the value of $title.

Password Input

“read-host” can be used to accept the password input.

$variable = Read-Host -AsSecureString " prompt "

Example 6.7

$pwd=Read-Host -AsSecureString "Please input password"

# assumes you will input ‘12345’ .

Please input password:     *****

Explanation:

The password will be stored in $pwd. But you are not able to see what the password is.

Example 6.8

$pwd     # to see the password

System.Security.SecureString       # this is an output

Explanation:

“$variable = Read-Host –AsSecureString” is used to accept the input of a password.

Replacement

In a text, a string can be replaced by another string.

"text" -replace "string1", "string2"

“string1” will be replaced by the “string2”

Example 6.9

"Go in 8 Hours" -replace "Go", "C#"

C# in 8 Hours

Explanation:

“Go” was replaced by “C#”

“-replace” and “-ireplace” is used for case insensitive replacement.

“-creplace” is used for case sensitive replacement.

Example 6.10

"Go in 8 Hours" -creplace "go", "C#"

Go in 8 Hours

Explanation:

“-creplace” is used for case sensitive replacement. So the replacement fails.

String Operators

When we operate the string, we need the operators.

*

Represents one string

e    . g. “C++ in 8 Hours”  -like “*”

+

Connects two strings

e    . g.   “JavaScript” + “in 8 Hours”

-replace,  -ireplace

Replace a string, case insensitive

e    . g.   “Kotlin in 8 Hours”  -ireplace  “Kotlin” , “Django”

-creplace

Replace a string, case sensitive

e    . g.   “Go in 8 Hours”  -creplace  “go” , “C#”

-eq,  -ieq

Check equality,  case insensitive

e    . g.   “JQuery in 8 Hours”  -ieq  “jQuery in 8 Hours”

-ceq

Check equality,  case sensitive

e    . g.   “HTML in 8 Hours”  -ceq  “Html in 8 Hours”

-like,  -ilike

Check similarity,  case insensitive

e    . g.   “Java in 8 Hours” -ilike “J*”

- clike

Check similarity,  case sensitive

e    . g.   “jQuery in 8 Hours” -clike “J*”

-notlike,  -inotlike

Check inquality,  case insensitive

e    . g.   “Python in 8 Hours” -inotlike “Pg”

-cnotlike

Check inquality,  case sensitive

e    . g.   “Rust in 8 Hours” -cnotlike “RU”

-match,  -imatch

Check equivalence,  case insensitive

e    . g. “Scala in 8 Hours” -imatch “s*”

-cmatch

Check equivalence,  case sensitive

e    . g. “PHP MySQL in 8 Hours” -cmatch “php*”

-notmatch,  -inotmatch

Check inequivalence,  case insensitive

e    . g. “Html Css in 8 Hours” -inotmatch “H*”

-cnotmatch

Check inequivalence,  case sensitive

e    . g. “Visual Basic in 8 Hours” -cnotmatch “V*”

Format String

“ -f ” can specify an output format of a string.

“myString {num1} {num2} {num3}”     -f arg1, arg2, arg3, ...

The num1, num2, num3 will be respectively replaced by the arg1, arg2, arg3.

Example 6.11

“Java {0} {1} {2}” -f "in", (2*4), “Hours”

# Output:

Java in 8 Hours

Explanation:      The {0}, {1}, {2} will be replaced respectively by the arg1, arg2, arg3 of the -f .

Example 6.12

“ActionScript {2} {0} {1}” -f "in", (2*4), “Hours”

# Output:

ActionScript Hours in 8          # different sequence

Explanation:      The {0}, {1}, {2} will be replaced respectively by the arg1, arg2, arg3 of the -f .

String Method

To create a String object:

$myString = “ text ”       # $myString is a string object

To use a String method:

$myString    . method()

Example 6.13

$str="jQuery in 8 Hours"

$str.ToUpper()      # convert to uppercase

JQUERY IN 8 HOURS

$str.Contains("Q")      # check if contains Q

True

Explanation:

“ToUpper()” is a method which is used to convert a string to uppercase.

“Contains()” is a method which is used to check if the string contains a specified character.

String Object Methods

CompareTo()

Comapre to another string

e . g . (“GOOD”) . CompareTo(“Good”)

Contains()

Check if contains a specified substring .

e . g . (“Good”) . Contains(“od”)

EndsWith()

Check if end with a specify substring .

e . g . (“Excellent”) . EndsWith(“ent”)

Equals()

Check if equal to another string .

e . g . (“string1”) . Equals("string2")

IndexOf()

Returns the index of the first match .

e . g . (“Excellent”) . IndexOf(“e”)

IndexOfAny()

Returns the first matching index of any character in the string .

e . g . (“Excellent”) . IndexOfAny(“len”)

Insert()

Inserts a string at the specified location

e . g . (“R in 8 Hours”) . Insert(0,"Learn ")

GetEnumerator()

Enumerate all characters in a string .

e . g . (“Excellent”) . GetEnumerator()

LastIndexOf()

The last matching position of the character .

e . g . (“Excellent”) . LastIndexOf(“e”)

LastIndexOfAny()

The last matching position of any character

e . g . (“Excellent”) . LastIndexOfAny(“ce”)

PadLeft()

Fill in the blanks on the left

e . g . (“Good”) . PadLeft(8)

PadRight()

Fill in the blanks on the right

e . g . (“OK ! ”) . PadRight(8) + “Good ! ”

Remove()

Removes the specified length from the specified position

e . g . (“Excellent”) . Remove(3,2)

Replace()

Repladce the specified string

e . g . (“Excellent”) . Replace("cel","aaa")

Split()

Cuts the string with the specified delimiter

e . g . (“Excellent”) . Split(“e”)

StartsWith()

Check if start with the specified substring

e . g . (“Excellent”) . StartsWith(“Ex”)

Substring()

Extracts a specified length substring from a specified position

e . g . (“Excellent”) . Substring(3,4)

ToCharArray()

Convert to character array

e . g . (“Excellent”) . ToCharArray()

ToLower()

Convert to lower case

e . g . (“Excellent”) . ToLower()

To Upper()

Convert to upper case

e . g . (“Excellent”) . ToUpper()

Trim()

Remove Spaces before and after the string

e . g . (“  Excellent  ”) . Trim()

TrimStart()

Remove the space at the beginning of the string

e . g . (“  Excellent  ”) . TrimStart()

TrimEnd()

Remove Spaces at the end of the string

e . g . (“  Excellent  ”) . TrimEnd()

Chars()

Returns the character at the specified position

e . g . (“Excellent”) . Chars(2)

Hour 7

Object

Object

Object refers to a concrete something. For example:  a car, a book, a dog, a house, etc…

The syntax to create an object is as follows:

$myObj = New-Object object

“$myObj = New-Object object” creates an object named “myObj”.

Example 7.1

$Service=New-Object object

$Service

System    . Object

Explanation:

“$Service=New-Object object” creates a new object named “$Service”

From the output, you can know that the attribute of $Service is a “System. Object”.

About New-Object

If we want to know more about the command “New-Object”, we can use “Help New-Object”

Help New-Object

Example 7.2

Help New-Object

NAME

New-Object

SYNTAX

New-Object [-TypeName] <string> [[-ArgumentList] <Object[]>]

New-Object [-ComObject] <string> [-Strict] [-Property <IDicti

ALIASES

None

REMARKS

Get-Help cannot find the Help files for this cmdlet on this c

-- To download and install Help files for the module that

-- To view the Help topic for this cmdlet online, type: "

go to http://go    . microsoft. com/fwlink/?LinkID=113355......

Explanation:      “Help New-Object” help you know more about the syntax and aliases of “New-Object”.

DateTime Object

The syntax to create a Datetime object is as follows:

$myObj = New-Object   System    . DateTime yyyy/m/d  h, m, s

The above command creates a datetime object and set a datetime with the parameters such as year, month, date, hour, minute, second

Example 7.3

$date = New-Object  System.DateTime  2019,7,4, 10,30,0

$date

July  4,  2019  10    : 30: 00

Explanation:

“$date=New-Object  System. DateTime  2019,7,4, 10,30,0” creates a DateTime object, and sets a datetime with the parameters such as year, month, date, hour, minute, second.

Object Member

Object Member refers to the properties and methods of an object.

Property describes what an object is. Method() indicates what an object can do. The syntax to know the object members is:

$myObj     | Get-Member

Example 7.4

We have created an object $date in a previous page . Now we want to know about the methods and properties of the $date.

$date | Get-Member

TypeName: System. DateTime

Name                 MemberType     Definition

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

Add                  Method         datetime Add(timespan value)

AddDays              Method         datetime AddDays(double value)

AddHours             Method         datetime AddHours(double value)

…..

Date                 Property       datetime Date {get;}

Day                  Property       int Day {get;}

……

Explanation:

“ $date | Get-Member ” can know the methods and properties of $data.

Object Method

Method() indicates what an object can do.

The syntax to use the method of an object is as follows:

$myObj    . Method()

Example 7.5

We have created an object “$date” in the previous page .

$date.AddDays(10)

July  14,  2019  10    : 30: 00

Explanation:

Originally the datetime of $date was “July  4,  2019  10: 30: 00”

After adding 10 days on $date,

Now the datetime of $date is “July  14,  2019  10: 30: 00”.

Object Property

The object property indicates what an object is.

The syntax to reference the property of an object is:

$myObj    . Property

Example 7.6

We have created an object “$date” in the previous page .

$date.Month

7

Explanation:

Originally the datetime of $date was “July  4,  2019  10: 30: 00”, which means the month of $date is July, therefore, the program returns 7.

Add Property

We sometimes need to add some properties to an object.

$myObje     | Add-Member NoteProperty Variable Value

Example 7.7

$fruit = New-Object object

$fruit | Add-Member NoteProperty Fruit Color

$fruit | Add-Member NoteProperty Apple Red

$fruit | Add-Member NoteProperty Pear Yellow

$fruit | Add-Member NoteProperty Grape Green

$fruit | Add-Member NoteProperty Blueberry Blue

$fruit | Add-Member NoteProperty Tangerine Oringe

$fruit

Fruit     : Color

Apple     : Red

Pear      : Yellow

Grape     : Green

Blueberry : Blue

Tangerine : Oringe

Explanation:

“$fruit = New-Object object” create an object named “fruit”.

“$fruit | Add-Member NoteProperty Apple Red” add a property and value “Apple Red”.

Add Method

We sometimes need to add some methods to an object.

$myObj | Add-Member ScriptMethod name { code… }

Example 7.8

$fruit = New-Object object

$fruit | Add-Member ScriptMethod eat { "Wow! Yummy!" }

$fruit | Add-Member ScriptMethod taste { "OK! Delicious!" }

$fruit.eat()           # call the method

Wow! Yummy!

$fruit.taste()         # call the method

OK    ! Delicious!

Explanation:

“$fruit | Add-Member ScriptMethod eat { "Wow! Yummy! " }” adds a method eat() to object “$fruit”.

“$fruit. eat()” calls the method “eat()”

“$fruit | Add-Member ScriptMethod taste { "OK! Delicious! " }” adds a method taste() to object “$fruit”.

“$fruit. taste()” calls the method “taste()”.

Check Property

We can check the property of an object:

$myObj | Get-Member -memberType NoteProperty

Example 7.9

$fruit = New-Object object

$fruit | Add-Member NoteProperty Fruit Color

$fruit | Add-Member NoteProperty Apple Red

$fruit | Add-Member NoteProperty Pear Yellow

$fruit | Add-Member NoteProperty Grape Green

$fruit | Add-Member NoteProperty Blueberry Blue

$fruit | Add-Member NoteProperty Tangerine Oringe

$fruit | Get-Member -memberType NoteProperty

TypeName: System. Object

Name      MemberType   Definition

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

Apple     NoteProperty System. String Apple=Red

Blueberry NoteProperty System. String Blueberry=Blue

Fruit     NoteProperty System. String Fruit=Color

Grape     NoteProperty System. String Grape=Green

Pear      NoteProperty System. String Pear=Yellow

Tangerine NoteProperty System    . String Tangerine=Oringe

Explanation:

“$fruit | Get-Member -memberType NoteProperty” can view the properties of $fruit.

Check Method

We can check the method of an object:

$myObj | Get-Member -memberType ScriptMethod

Example 7.10

$fruit = New-Object object

$fruit | Add-Member ScriptMethod eat { "Wo w! Yumm y! " }

$fruit | Add-Member ScriptMethod taste { "O K! Deliciou s! " }

$fruit | Get-Member  -memberType  ScriptMethod

TypeName: System . Object

Name  MemberType   Definition

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

eat   ScriptMethod System . Object eat();

taste ScriptMethod Syste    m . Object taste();

Explanation:

“$fruit | Get-Member  -memberType  ScriptMethod” can view the methods of the $fruit.

Hour 8

Pipeline

PowerShell Pipeline

PowerShell is the shell language for Windows, which makes it easier to operate Windows System with the command line of an administrator.

The symbol of the pipeline is “ | ”.

The following is some common pipeline commands:

command | Foreach-Object  -parameters

Usage: Traverse the collection .

command | Where-Object  -parameters

Usage: Filter the data

command | Select-Object  -parameters

Usage: Selects specified properties of an object

command | Sort-Object  -parameters

Usage: Sort the object data

command | Tee-Object  -parameters

Usage: Save the output in a file or variable

command | Group-Object  -parameters

Usage: Group objects by properties

command | Measure-Object  -parameters

Usage: Perform statistics, get min, max, average values

command | Compare-Object  -parameters

Usage: Compares two objects or two collections

Foreach-Object

“Foreach-Object” is used to traverse each element of a collection.

command | Foreach-Object -begin{}  -process{}  -end{}

-begin is a pre-processing action

-process is an operation that processes data

-end is an operation after processing

Example 8.1

0 . . 5 | Foreach-Object -begin {"go"} -process { "done $_" } -end {"ok"}

go

done 0

done 1

done 2

done 3

done 4

done 5

ok

Explanation:

“0.. 5” is a collection.   $_ represents the current element.

“Foreach-Object” traverse each element of a collection.

Where-Object

“Where_Object” is used to filter data. The alias is “? ”.

command | Where-Object  -parameters{ }

The following example views the computer services with the name “A ” .

Example 8.2

Get-Service | Where-Object {$_.Name -like "A*"}

Status   Name               DisplayName

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

Stopped  AeLookupSvc        Application Experience

Stopped  ALG                Application Layer Gateway Service

Running  AlibabaProtect     Alibaba PC Safe Service

Stopped  AppIDSvc           Application Identity

Stopped  Appinfo            Application Information

Stopped  AppReadiness       App Readiness

Stopped  AppXSvc            AppX Deployment Service (AppXSVC)

Running  AudioEndpointBu .. . Windows Audio Endpoint Builder

Running  Audiosrv           Windows Audio

……

Explanation:

“Get-Service” checks the computer service.

Select-Object

“Select-Object” is used to select specified properties of an object or set of objects.

command | Select-Object  -parameters

Example 8.3

Get-Process | Select-Object ProcessName

ProcessName

-----------

acrotray

conhost

dasHost

dllhost

dwm

explorer

hkcmd

Idle

igfxtray

ktpcntr

notepad

powershell

……

Explanation:

“Get-Process” checks the processes the computer is running.

Sort-Object

“Sort-Object” is used to sort the object data.

command | Sort-Object  -parameters

Example 8.4

Get-Service | Sort-Object -Property DisplayName

Status     Name                DisplayName

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

Stopped  AxInstSV           ActiveX Installer (AxInstSV)

Running  AlibabaProtect     Alibaba PC Safe Service

Stopped  AppReadiness       App Readiness

Stopped  BaiduUpdater       Baidu Updater

Running  BFE                   Base Filtering Engine

Stopped  bthserv              Bluetooth Support Service

Stopped  CertPropSvc        Certificate Propagation

Running  KeyIso               CNG Key Isolation

Running  Browser             Computer Browser

Running  DcomLaunch      DCOM Server Process Launcher

……

Explanation:

“Sort-Object  -Property DisplayName” sorts the service information by the “DisplayName”.

Tee-Object

“Tee-Object” is used to save the output to a file in the specified directory, or to a variable.

command | Tee-Object  -parameters

Note: Before you use Tee-Object command, you must create a new text file in C:/Users/YourName/ myFile.txt

Example 8.5

Get-Service | Tee-Object -filepath C:/Users/Ray/myFil e. txt

Status     Name                DisplayName

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

Stopped  AxInstSV           ActiveX Installer (AxInstSV)

Running  AlibabaProtect     Alibaba PC Safe Service

Stopped  AppReadiness       App Readiness

Stopped  BaiduUpdater       Baidu Updater

Running  BFE                   Base Filtering Engine

Stopped  bthserv              Bluetooth Support Service

Stopped  CertPropSvc        Certificate Propagation

Running  KeyIso               CNG Key Isolation

Running  Browser             Computer Browser

Running  DcomLaunch      DCOM Server Process Launcher

Running  DeviceAssociati .. . Device Association Service

……

When you open the “ myFile.txt ”, You can see the service information in the file .

Display:

Status     Name               DisplayName

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

Stopped  AxInstSV           ActiveX Installer (AxInstSV)

Running  AlibabaProtect     Alibaba PC Safe Service

Stopped  AppReadiness       App Readiness

Stopped  BaiduUpdater       Baidu Updater

Running  BFE                   Base Filtering Engine

Stopped  bthserv              Bluetooth Support Service

Stopped  CertPropSvc        Certificate Propagation

Running  KeyIso               CNG Key Isolation

Running  Browser            Computer Browser

Running  DcomLaunch      DCOM Server Process Launcher

Running  DeviceAssociati... Device Association Service

……

Explanation:

“Tee-Object -filepath C:/Users/Ray/myFile. txt” saves the service information to a file in the path C:/Users/Ray/myFile. txt.

Group-Object

“Group-Object” is used to group objects by properties

command | Group-Object  -parameters

Example 8.6

PS C:\Users\RAY> get-childitem | group-object  extension

Count Name                Group

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

1 . eclipse                  { . eclipse}

1 . scalac                   { . scalac}

1 . tooling                   { . tooling}

1 . txt                          {myFile . txt}

1     . ps1                        {MyScript . ps1}

Explanation:

“get-childitem” gets all folder names and file names in the path “C: \Users\RAY”. ( The childitem of your computer is different with mine. )

“group-object  extension” groups the folders and files by extension name.

“Count” represents the number of items in each group.

“Name” represents the values of the extension name.

“Group” represents the object(s) in each Group.

Measure-Object

“Measure-Object” is used to perform the statistics, such as get min, max, average values.

command | Measure-Object  -parameters

Example 8.7

$list = 2,5,16,28,32,69,88

$num = $list | Measure-Object -Minimum -Maximum

$num.Minimum

# Output

2

$num.Maximum

# Output

88

Explanation:

“$list | Measure-Object -Minimum -Maximum” performs the statistics for the $list.

“$num. Minimum” gets the minimum value of the $num.

“$num. Maximum” gets the maximum value of the $num

Compare-Object

“Compare-Object” is used to compare two objects or two collections.

compare-object -referenceobject $var1 -differenceobject $var2

“-referenceobject $var1” represents the first object

“differenceobject $var2” represents the second object

The comparison result is the difference of the two objects.

Example 8.8

$p1= get-process

notepad      # open a notepad, run one more process

$p2 = get-process

compare-object -referenceobject $p1  -differenceobject $p2

# Output

InputObject                                                              SideIndicator

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

Syste    m . Diagnostics . Process (notepad)                                 =>

Explanation:

“$p1= get-process” checks the process at the first time.

“notepad” command opens the notepad, the purpose is to run one more process for the next comparison.

“$p2 = get-process” checks the process at the second time.

At this moment, process1 surely is different with the process2. Because after the pocess1, the notepad was opened, one more process has been running. Therefore, the process2 is different to process1.

“InputObect” shows the different status.

The “System. Diagnostics. Process (notepad)” is the difference of two processes.

Appendix 1

Error

Sometimes we need to check any error in the code:

“If($?) ” checks the status of error.

If it returns true, means no error.

If it returns false, means there is an error    .

To suppress the built-in error message:

-ErrorAction   "SilentlyContinue"

Assume that we want to remove a file that doesn't exist.

Example A1

Remove-Item "ABCD E. txt"  -ErrorAction  "SilentlyContinue"

If ($?) {       # Actually ABCD E . txt doesn’t exist

"File removed successfully";

break

};

"File removed unsuccessfull y! "

# Output:

File removed unsuccessfull    y !

Explanation:

“Remove-Item” command is used to remove specified object.

Exception

PowerShell uses “Try-Catch Statement” to resolve the exception.

try{

# exception may happen in here

}

catch{

# catch the exception

}

Example A2

try{

.\ABCDE.txt     # try to access this file

}

catch{      # but ABCDE . txt file doesn’t exist

"An exception is caught, the file does not exist."

$_.Exception.Message      # show exception message

}

# Output:

An exception is caught, the file does not exist.

The    . \ ABCDE. text item could not be recognized as the name of the cmdlet, function, script file, or runnable program. Check the spelling of the name, if the path is included.

Explanation:

Access a file that doesn’t exist, so an exception occurred.

Trap Exception

Trap command can catch the exception and display the exception message.

trap {

exception message

continue

}

exception code

Example A3

trap{

"Trap command catches an exception"

$_.Exception.Message

continue

}

100/0       # exception code in here

# Output:

Trap command catches an exception

Try dividing by zero

Exception:

“trap” catches an exception and shows an exception message.

“100/0” is an exception code.

Appendix 2

Tests

Please fill in a correct answer.

01.

The format of PowerShell command is _______.

02.

__________ can get the data type of various data.

03.

The operator of negation is _______.

04.

__ represents the current element in the current loop.

05.

To define a function, use ____________________.

06.

______________ creates an object named “myObj”.

07.

The string included with the ———— will return original content.

08.

________ is used to traverse each element of a collection.

09.

__________ gets the command alias.

10.

__________ defines a variable with Date Time type.

11.

_____ makes the value of $x increasing 1.

12.

_____ loop is used to iterate throughout the each element in a collection .

13 .

________ defines a function with the switch parameters.

14.

The syntax to create an object is ________

15.

The __________ format can define multi-line String.

16.

________ command is used to save the output to a file in the specified directory.

17.

_______ command can know about the service the computer provides.

18.

The syntax to access the array is _______.

19.

_________  is an operator that means not include .

20 .

“do / ______” loops through a block of code once first, and then repeats the loop if the specified condition is true.

21.

_________ can define a Filter function.

22.

The syntax to reference the property of an object is ______

23.

_________ command is used to accept the input from users.

24.

_________ is used to perform the statistics, such as get min, max, average values.

25.

The syntax to view the contents of the PowerShell file “myfile. psl” is ________.

26.

The syntax to clone an array is _________.

27.

“-lt” means __________ .

28.

Trap command is used to ________.

29.

The syntax to call a pipeline function is __________.

30.

The syntax to know the object members is ___________.

31.

______________ is used to accept the input of a password.

32.

___________ is used to group objects by properties.

33.

_______ checks the status of error.

Answers

01.   verb – noun

02.   (data). gettype(). name

03.   -not

04.   $_

05.   function function_name { }

06.   $myObj = New-Object object

07.   single quotes

08.   Foreach-Object

09.   Get-Command -CommandType Alias

10.   [Date Time] $variable = value

11.   $x++

12.   Foreach

13.   function  func_name([switch] $arg) { }

14.   $myObj = New-Object object

15.   @”  text “@

16.   Tee-Object

17.   Get-Service

18.   $array_name[ index ]

19.   –noncontains

20 .   while

21 .    filter func_name(){  }

22.   $myObj. Property

23.   read-host

24.   Measure-Object

25.   Get-Content . / myfile. ps1

26.   $array2 = $array1. Clone()

27.   less

28.   catch exception and show exception message.

29.   command | pipeline function.

30.   $myObj | Get-Member

31.   $variable = Read-Host –AsSecureString

32.   Group-Object

33.   If($?)

Note:

This book is only for beginners, it is not suitable for experienced programmers.

PowerShell Source Code Download Link:

https://forms . aweber . com/form/97/1907095997 . htm

Source Code Download

PowerShell Source Code Download Link:

https://forms . aweber . com/form/97/1907095997 . htm

Node.Js

Hour 1

Introduction

Node . Js Introduction

What is Node.Js

Nod e . js is a server platform built on Google Chrome's JavaScript engin e . It is an open source, cross-platform running environment for server and network application s . The nod e . js application is written in JavaScript and runs at nod e . js runtime in OS X, Microsoft Windows, and Linu x .

Node. js also provides rich JavaScript libraries for various modules, it is convenient for the research and development of web applications to a large extent.

A lot of companies such as eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, Wikipins, Yahoo! and Yammer are using Node. js all the time.

The node. js interpreter will be used to interpret and execute JavaScript code.

Node. js editor includes: Windows notepad, OS Edit command, Brief, Epsilon, EMACS and VIM or Vi.

The extending name of a node. js file is ". js".

Node. js = Running environment+ JavaScript libraries

Who is suitable to read this tutorial?

If you're a front-end programmer who doesn't know dynamic programming languages like Java, C++, or Python, and you want to create your own services, node. js is a great choice.

Node. js is one kind of JavaScript that runs on the service side. If you are familiar with JavaScript, you will learn node. js easily.

Of course, if you're a back-end programmer and want to deploy some high-performance services, node. js is a great language to learn.

Who is using node.js?

The following is a list of companies that use node. js: including eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, Yahoo! Wikipins, and Yammer…etc.

Node . Js Installation

Download

Installing node. js on Windows is convenient, and you only need to access node. js's official website

Download Link:     http : //www . nodejs . org/

Installation

After the download is complete, double-click the installation package directly, just like any other software installation…...

……

Select a default installation folder……

……

Complete the installation.

Click “Finish” button.

First Node . Js Code

Example 1.1

Click the Menu Start > All Programs > Node.js Folder > Node.js   (green icon). You can see the Node. js interface.

Please input the following node. js code:

console. log("Hello, World! ");

Press “Enter” key.

Output:

Hello World

Explanation:

“console. log(…)”  is an output command, which is used to output some texts.

Each command of Node. js should be ended by a semicolon (; ).

For example:

The command “console. log( "C# in 8 Hours" ); ” will output the text “C# in 8 Hours”.

Calculation by Node . Js

Click the Menu Start > All Programs > Node.js Folder > Node.js

You can see the Node. js interface.

Run some simple arithmetic calculations as follows:

> 100 + 200

300

> 300 - 50

250

> 2 * 300

600

> 27 / 3

9

> 100 % 2

0

>

Variable

The syntax to declare a variable is as follows:

var variable = value

Example 1.2

> var x =100, y = 200;

undefined

> x + y

300

> var a = "Scala";

undefined

> var b = " in 8 Hours"

undefined

> console. log( a + b )

Scala in 8 Hours

undefined

Explanation:

“var” keyword is used to declare a variable.

“ _ ” variable

An underline “ _ ” symbol can represent a previous arithmetic expression.

Example 1.3

> var m = 100, n = 2;

undefined

> m * n

200

> var result = _

undefined

> console. log(result)

200

undefined

Explanation:

“ _ ” represents the above expression “ m * n ”.

Node . Js Comment

“ // ” symbol can be used for a comment. It is always ignored by the node. js interpreter.

//  this is node.js comment

Example 1.4

> var str = "C++ in 8 Hours"      // define a variable

undefined

> console. log(str)       // output a value of the variable

C++ in 8 Hours

undefined

Explanation:

“// define a variable ” and “// output a value of the variable ” are Node. js comments, which are ignored by the Node. js interpreter.

Run Node . Js Program

Create a Working Folder

Please go to C: \Users\YourName, create a folder “myNode ”. Now the working folder is “C: \Users\YourName\myNode ”, which is used to save Node files.

Example 1.5

Please open the Windows NotePad, write the following code in it.

var x = "JavaScript ";

var y = "in 8 Hours";

var str = x + y;

console    . log(str);

Save the file as “myFile. js” in the working folder “myNode”.

"Start" > " Run" > type "cmd ". Open the “cmd ” command prompt,  type “cd \Users\YourName\myNode”,

go to “C: \Users\YourName\myNode”.

Type “node  myFile. js”, run the program.

Output:

JavaScript in 8 Hours

Explanation:

You need to create a working folder “myNode” as follows:

C: \Users\YourName\myNode.

Save the myFile. js file to the working folder “myNode”.

Open the “cmd ” command prompt,

type “cd \Users\YourName\myNode”,

go to “C: \Users\YourName\myNode”, type “node myfile.js ”, run the program “myFile. js”.

“console. log(str);” outputs the value of the variable “str”.

The syntax to run a node. js program is as follows:

node  myFile    . js

Hour 2

Basics

Node . Js Function

Function is a code block that can be used repeatedly.

The syntax to define a Node function is as follows:

function Funcion_Name(){…}

The syntax to call the function is as follows:

Function_Name();

Example 2.1

function fun(str) {    // define a function “fun”

console. log(str);

}

fun("MySQL in 8 Hours    ! ");    // call a function “fun”

Output:

MySQL in 8 Hours!

Explanation:

“function fun(str) {…}” defines a function “fun”.

“fun(…)” calls a function “fun”.

Imbedded Function

In node. js, one function can word as an argument of another function, which means one function can imbed another function.

Example 2.2

function fun1(str) {

console. log(str);

}

function fun2(myFun , str) {

myFun(str);

}

fun2(    fun1 , "Good! ");     // call fun2

Output:

Good!

Explanation:

“fun2(fun1 , "Good! ");”: Its first argument is a function fun1.

When the fun2 is called, the fun1 as an argument is passed to myFun. Therefore, “myFun” is equal to “fun1”.

“myFun(str);” executes the function fun1(str){ }.

“Good! ” as the second argument is passed to “str” variable.

Anonymous Function

The anonymous function has no a function name.

The syntax to define an anonymous function is as follows:

function(){… }

Example 2.3

function fun(myFun, str) {

myFun(str);

}

fun( function(str){ console.log(str) } , "OK! " );   // call fun

// the first argument is “function(str){ console . log(str)” .

// the second argument is “OK ! ” .

Output:

OK!

Explanation:

“function(str){ console. log(str)” is an anonymous function.

When “function fun” is called, the first argument “function(str){ console. log(str)” is passed to “myFun”, therefore, “function(str){ console. log(str)” is equal to “myFun”.

The second argument is passed to “str” variable.

Callback Function

The callback function is called when the task is completed or when an error occurs.

function(param1, param2,     callback(){ } )

A callback function usually words as the last parameter.

Now let’s learn how to use the callback function.

The syntax to rename a file is as follows:

fs    . rename("oldFile", "newFile", callback )

“fs” is a file module, which is used to process files.

Example 2.4

// Assume there is already a file aaa . txt in the folder “myNode”

var fs = require("fs");

console. log("This is a sample to rename a file! ");

fs. rename("aaa. txt", "bbb. txt", function(err) {

if (err) {

return console. error(err);

}

console. log("aaa. txt has renamed as bbb. txt successfully! ");

});

Output:

This is a sample to rename a file!

aaa. txt has renamed as bbb. txt successfully!

Explanation:

“fs” is a file module, which is used to process files.

Assume there is already a file aaa. txt in the folder “myNode”.

“fs. rename("aaa. txt", "bbb. txt", function(err)” renames aaa. txt as bbb. txt.

In this example, the callback function has not yet been called because no error occurs.

If an error occurs, the callback function will be called.

Example 2.5

// Assume that there is no a file ccc . txt in the folder “myNode”

var fs = require("fs");

console. log("This is a sample to rename a file! ");

fs. rename("ccc. txt", "ddd. txt", function(err) {

if (err) {     // if an error occurs, the callback function is called

return console. error(err);

}

console. log("Try to rename ccc. txt as ddd. txt. ");

});

Output:

This is a sample to rename a file!

{ [Error: ENOENT: no such file or directory,……] }

Explanation:

Because the file ccc. txt is not existing, an error occurs, the callback function is called and the error message is shown.

Event

Node. js provides asynchronous callback interfaces, through which a large amount of concurrency can be handled, so the performance of Node. js is very high. Node. js generates an event listener for each event and calls the callback function if an event occurs.

The following 4 steps can listen and resolve the event.

(1) Import an Event Module

var events = require('events');

(2) Create an Event Object

var eventObject = new events    . EventEmitter();

(3)  Bind the Event to a Callback Function.

eventObject    . on('eventName', function(){…});

(4) Triggers the Event

eventObject    . emit('eventName');

Example 2.6

// import events module

var events = require('events');

// create an event object

var eventObj = new events. EventEmitter();

// bind Event001 event to the callback function

eventObj. on('Event001', function(){

console. log('Event001 Done! ');

});

// bind Event002 event to the callback function

eventObj. on('Event002', function(){

console. log('Event002 Done! ');

});

// trigger Event001 event

eventObj. emit('Event001');

// trigger Event002 event

eventObj. emit('Event002');

console    . log ("All events are done successfully! ");

Output:

Event001 Done!

Event002 Done!

All events are done successfully!

Explanation:

“require('events');” imports the “events” module.

“new events. EventEmitter();” creates an event object.

“eventObj. on('Event001', function(){…})” binds the Event001 to a callback function.

“eventObj. emit ('Event001');” triggers the Event001 event.

“eventObj. on('Event002', function(){…})” binds the Event002 to a callback function.

“eventObj. emit ('Event002');” triggers the Event002 event.

This program imports the events module, and instantiates the EventEmitter class to bind and listen for events.

EventEmitter Class

The events module provides the EventEmitter class, which works for both an event trigger and an event listener.

Let’s review the whole event process:

// import event module

var events = require('events');

// create an event object

var eventObject = new events. EventEmitter();

// bind the event to a callback function

eventObject. on('event_name', function() { });

// trigger the event

event    . emit('event_name');

Example 2.7

console. log('You can see the next message in 6 seconds: ')

var EventEmitter = require('events')    // import event module

var eventObj = new EventEmitter();     // create an event object

eventObj. on('delayEvent', function() {   // bind event to callback

console. log('The event delays 6000 milliseconds');

});

setTimeout(function() {        // this is a delay function

eventObj. emit('delayEvent');       // trigger an event

}, 6000);          // 6000 milliseconds

Output :

You can see the next message in 6 seconds:

The event delays 6000 milliseconds

Explanation:

“require('events')”imports the event module.

“new EventEmitter();” creates an event object

“eventObj. on('delayEvent', function() {…}); binds the event to the callback function.

“setTimeout(function() {…}, time);” is a delay function. Note: It contains a callback function. Its second parameter is a delay time.

“6000” means 6 seconds.

“eventObj. emit('delayEvent');” triggers an event.

Methods of EventEmitter

EventEmitter provides many methods. For example: The “on method” is used to bind an event and the callback function. The “emit method” is used to trigger an event.

The methods of EventEmitte are as follows:

Methods & Descriptions

addListener(event listener)

Add a listener for an event .

on(event listener)

bind an event to the listener(callback function) .

once(event, listener)

bind an event to the one-time listener(callback function) .

listenerCount(event)

Count how many listeners working

removeListener(event, listener)

Remove a listener

removeAllListeners([event])

Remove all listeners

setMaxListeners(n)

Set the maximum number listeners

emit(event)

Trigger an event

Hour 3

Event

EventEmitter Examples

Example 3.1

// import "event" module

var events = require('events');

// create an event object

var eventObj = new events. EventEmitter();

// create listener1

var listener1 = function listener1() {

console. log('listener1 run. ');

}

// create listener2

var listener2 = function listener2() {

console. log('listener2 run. ');

}

// add listener1 to myEvent1

eventObj. addListener('myEvent', listener1);

// add listener1 to myEvent2

eventObj. addListener('myEvent', listener2);

// count how many listeners working

var number = eventObj. listenerCount('myEvent');

console. log( number + " listeners run");

// trigger myEvent event

eventObj. emit('myEvent');

// remove listener1

eventObj. removeListener('myEvent', listener1);

console. log("listener1 has been removed. ");

// trigger myEvent event

eventObj. emit('myEvent');

// count how many listeners working

number = eventObj. listenerCount('myEvent');

console. log( number + " listener run. ");

console    . log("Done! ");

Output:

2 listeners run

listener1 run.

listener2 run.

listener1 has been removed.

listener2 run.

1 listener run.

Done!

Explanation:

Review each comment on this program.

addListener(event  listener)

Add a listener to an event .

on(event  listener)

Bind an event to a listener(callback function) .

once(event, listener)

Bind an event to a one-time listener(callback function)

listenerCount(event)

Count how many listeners working

removeListener(event, listener)

Remove a listener

removeAllListeners([event])

Remove all listeners

setMaxListeners(n)

Set the maximum number listeners

emit(event)

Trigger an event

Error Event

In the node. js code where may some error occur, we can set an error event listener. EventEmitter defines an ‘Error’ event. When an error happens, ‘Error’ will quit the program and output some error messages.

Example 3.2

var events = require('events');

var obj = new events. EventEmitter();

obj    . emit('error ');     // set an “error” event to trigger

Output:

events. js: 189

throw err; // Unhandled 'error' event

^

Error [ERR_UNHANDLED_ERROR]: Unhandled error. (undefined)

at EventEmitter. emit (events. js: 187: 17)

at Object. <anonymous>

at Module. _compile (internal/modules/cjs/loader. js: 778:

at Object. Module. _extensions.. js (internal/modules/cjs/

at Module. load (internal/modules/cjs/loader. js: 653: 32)

……

Explanation:

The program outputs some error messages when an error occurs.

Node . Js Module

If a file need to import the code from another file, this another file is called a module. (In fact, a module is only an external file. )

(1) Create a module and export a function

exports    . function_name = function() {…}

(2) Import a module and will use the function.

var obj = require('    ./ module');

“ ./ ” means the current directory.

Example 3.3

// 1 . Create a module “moduleFile . js”

exports.myFun = function() {    // export a function myFun

console. log('Go in 8 Hours! ');

}

// 2 .  Create a file as “main . js” and run .

var obj = require('./moduleFile') ;     // import the moduleFile

obj    .myFun() ;        // call myFun

Output:

Go in 8 Hours

Explanation:

Two files should be saved in the same directory.

First, create a module and save the file as “moduleFile. js. ”

“exports. myFun = function() {…. }” exports a function “myFun”.

Second, create a main. js file and import the moduleFile. js

“var obj = require('./ moduleFile');” imports the moduleFile. js, and create a module object.

“obj. myFun();” calls the function “myFun”.

Node . Js Buffer

Node. js has a great advantage: it can process binary data, and character encoding.

Node. js includes a Buffer class that creates a Buffer area for processing binary data and character encoding.

It is possible to use the Buffer class whenever you process the file I/O stream operations in Node. js.

Node. js can process following character encodings:

Encoding

Description

ascii

an only 7 bits encoded of ascii data

utf8

a multi byte encoded of unicode characters

utf16le

2 or 4 bytes encoded of unicode characters

ucs2

the alias of utf16le

base64

base64 encoding

latin1

one-byte encoded of the string

binary

the latin1 of alias

hex

hexadecimal character encoding

Buffer objects

There are several methods to create Buffer objects.

The syntax to create the Buffer object is as follows    :

Buffer.alloc(size)

Creates a Buffer object of the specified size    . (safe)

Buffer.allocUnsafe(size)

Creates a Buffer object of the specified size    . (unsafe).

Buffer.from(array)

Create a Buffer object initialized with an array

Buffer.from(buffer)

Create a Buffer object with the data of another buffer object

Buffer.from(‘string’)

Create a Buffer object initialized with a string

Create a Buffer Object (1)

Buffer object is usually used to process character encoding.

The syntax to create an object of Buffer is as follows:

const obj = Buffer    . from('string');

Example 3.4

const obj = Buffer. from('RayYao');     // create a Buffer object

console. log(obj. toString('ascii '));     // output asscii encoding

console. log(obj. toString('hex '));       // output hex encoding

console    . log(obj. toString('base64 '));     // output base64 encoding

Output:

RayYao

52617959616f

UmF5WWFv

Explanation:

“const obj = Buffer. from('RayYao');” creates a Buffer object.

“console. log(obj. toString('ascii '));” outputs asscii encoding

“console. log(obj. toString('hex '));” outputs hex encoding

“console. log(obj. toString('base64 '));” outputs base64 encoding

Create a Buffer Object (2)

The syntax to create a buffer object based on the size is:

const buf = Buffer    . alloc(size);

Example 3.5

const buf = Buffer.alloc(6);

console    . log(buf);

Output:

<Buffer 00 00 00 00 00 00>

Explanation:

“buf” is a buffer object.

“const buf = Buffer. alloc(6);” creates a buffer object with six bytes.

“console. log(buf);” outputs the data of the buf.

“Buffer. alloc(size)” creates a safe buffer, because it always clear all previous data in the buffer.

Create a Buffer Object (3)

The syntax to create a buffer object based on the size is:

const buf = Buffer    . allocUnsafe (size);

Example 3.6

const buf = Buffer.allocUnsafe(6);

console    . log(buf);

Output:

<Buffer 0e 5c 10 3a 26 02>

Explanation:

The output may be different from yours.

“const buf = Buffer. allocUnsafe(6);” creates an unsafe buffer object with six bytes. But the unsafe buffer runs faster than the safe buffer.

This buffer is unsafe; it may contain some previous sensitive data.

Therefore, it needs to be initialized by using fill (0).

Fill Function

Because the “allocUnsafe(10)” create an unsafe buffer, we need to use fill() to clear the buffer , make it safe.

buf    . fill(0);

Example 3.7

const buf = Buffer. allocUnsafe(10);

console. log(buf);

buf.fill(0);      // fill buffer as 0

console    . log(buf);

Output:

<Buffer 08 07 10 c9 30 a1 02 05 60 e8>

<Buffer 00 00 00 00 00 00 00 00 00 00>

Explanation:

“buf. fill(0);” will make the data of the buffer zero.

“<Buffer 08 07 10 c9 30 a1 02 05 60 e8>” is the data created by “allocUnsafe(10)”. (The buffer data is different from yours. )

“<Buffer 00 00 00 00 00 00 00 00 00 00>” is the data created by “fill(0)”. (The buffer data are all zeros now. )

After using fill(0), the buffer is safe.

Hour 4

Write/Read

Write to Buffer

The syntax to write to buffer is as follows:

length = buf    . write(“string”)

length: the size of the string.

buf: the buffer object.

string: the characters that will be written to buffer.

Example 4.1

buf = Buffer. alloc(256);

len = buf.write ("MySQL in 8 Hours");

console    . log("The string length is : "+  len);

Output:

The string length is 16

Explanation:

“Buffer. alloc(256)” creates a buffer object with 256 bytes.

“buf. write(“…”)” writes a string to buffer.

Read from Buffer

The syntax to read a buffer is as follows:

buf    . toString(encoding, start, end)

encoding: such as ascii, base64, binary, hex, utf8(default)

start: buffer-reading starts from this index.

end: buffer-reading ends at this index.

Example 4.2

buf = Buffer.alloc (8);          // create a buffer object

buf[0] = 104;

buf[1] = 101;

buf[2] = 108;

buf[3] = 108;

buf[4] = 111;

buf[5] = 33;

console. log( buf.toString ('ascii'));

console. log( buf.toString ('ascii',0,6));

console. log( buf.toString ('utf8',0,6));

console    . log( buf.toString (undefined,0,6));

Output:

hello!

hello!

hello!

hello!

Explanation :

“buf = Buffer.alloc (8);” creates a buffer object with 8 bytes.

“buf[0] = 104;”:   “104” is ascii code, represents “h”.

“buf[1] = 101;”:   “101” is ascii code, represents “e”

“buf[2] = 108;”:   “108” is ascii code, represents “l”

…..

“buf. toString('ascii')” reads the buffer, encoding with ascii.

“buf. toString('ascii',0,6)” reads the buffer from index 0 to index 6, encoding with ascii.

“buf. toString('utf8',0,6)” reads the buffer from index 0 to index 6, encoding with utf8.

“buf. toString(undefined',0,6)” reads the buffer from index 0 to index 6, encoding with utf8 by default.

Buffer Length

The syntax to get the length of the buffer is as follows:

buf    . length;

Return the size of memory occupied by the Buffer object.

Example 4.3

var buf = Buffer. from('C# in 8 Hours');

console    . log("Buffer length: " + buf.length );

Output:

Buffer length: 13

Explanation:

“buf. length” returns the size of memory occupied by the Buffer object.

Buffer Merge

The syntax to merge two buffers is as follows:

buffer3 = Buffer    . concat(buffer1, buffer2);

“buffer 3” means the merged buffer.

Example 4.4

var buf1 = Buffer. from(('Kotlin '));

var buf2 = Buffer. from(('in 8 Hours'));

var buf3 = Buffer.concat([buf1,buf2]);

console    . log("The buf3 is: " + buf3. toString());

Output:

The buf3 is Kotlin in 8 Hours

Explanation:

“Buffer. concat([buf1,buf2])” merges two buffers.

“buf3” is a merged buffer.

Buffer Compare

The syntax to compare two buffers is as follows:

result = buffer1    . compare(buffer2);

The result may be equal to 0, greater than 0, or less than 0.

Example 4.5

var buffer1 = Buffer. from('100');

var buffer2 = Buffer. from('200');

var result = buffer1.compare(buffer2);

if(result < 0) {

console. log(buffer1 + " is less than " + buffer2);

} else if(result == 0) {

console. log(buffer1 + " is equal to " + buffer2);

} else {

console. log(buffer1 + "is greater than " + buffer2);

}

Output:      100 is less than 200

Explanation:

“buffer1. compare(buffer2);” compares two buffers.

Buffer Copy

The syntax to copy a buffer is as follows:

buffer2    . copy(buffer1, index);

Copy buffer2 to the specified position of the buffer1.

index: the specified position.

Example 4.6

var buf1 = Buffer. from('Java guide in 8 Hours');

var buf2 = Buffer. from('Script');

buf2.copy(buf1, 4);     // copy buf2 to the index 4 of buf1

console    . log(buf1. toString());

Output:

JavaScript in 8 Hours

Explanation:

“buf2. copy(buf1, 4);” copies buf2 to the index 4 of the buf1.

Buffer Slice

The syntax to get a buffer slice is as follows:

var buffer2 = buffer1    . slice(start,end);

“buffer2” is a new small buffer coming from buffer1.

start: the new buffer starts at this index.

end: the new buffer ends at this index.

Example 4.7

var buf1 = Buffer. from('Scala in 8 Hours');

var buf2 = buf1.slice(6,16);

console    . log("The buf2 content is: " + buf2. toString());

Output:

The buf2 content is: in 8 Hours

Explanation:

“buf1. slice(6,16);” gets a slice of the buf1 from index 6 to index 16.

Buffer Index

The syntax to get an index of a string in the buffer is as follows:

buf    . indexOf('string'));

Returns the index of the string.

Example 4.8

const buf = Buffer. from('Linux Shell in 8 Hours');

console. log(buf. toString());

console. log("The index of Shell is: "+ buf.indexOf ('Shell'));

console    . log("The index of Hours is: "+ buf.indexOf ('Hours'));

Output:

Linux Shell in 8 Hours

The index of Shell is: 6

The index of Hours is: 17

Explanation:

“buf. indexOf('Shell'));” returns an index of “Shell”.

“buf. indexOf('Hours'));” returns an index of “Hours”.

Buffer Equality

The syntax to check the buffer equality is as follows:

buffer1    . equals(buffer2);

Returns true or false.

Example 4.9

const buffer1 = Buffer. from('abc');

const buffer2 = Buffer. from('abc');

const buffer3 = Buffer. from('abcde');

console. log(buffer1.equals (buffer2));

console    . log(buffer1.equals (buffer3));

Output:

true

false

Explanation:

“buffer1. equals(buffer2)” checks if buffer1 is equal to buffer2.

“buffer1. equals(buffer3)” checks if buffer1 is equal to buffer3.

Buffer ASCII

The syntax to get an ASCII code of a character is as follows:

buf[index]

Returns an ASCII code of a character at the specified index.

index: an index of a character.

Example 4.10

const buf = Buffer. from('abcdefgh');

console. log(buf[2] );     // index 2 is "c"

console    . log(buf[6] );     // index 6 is "g"

Output:

99

103

Explanation:

The ASCII code of “c” is 99.

The ASCII code of “g” is 103.

Buffer to Json

A Buffer can be converted to a Json object.

var json = buf    . toJSON(buf);

“json” is a Json object, “buf” is a Buffer object.

Example 4.11

const buf = Buffer. from("Ray Yao");

var json = buf.toJSON(buf);    // convert to Json object

console    . log(json);     // show data in Json format

Output:

{ type: 'Buffer', data: [ 82, 97, 121, 32, 89, 97, 111 ] }

Explanation:

“var json = buf.toJSON(buf); ” converts the Buffer object to a Json object.

“console. log(json);” shows the data in Json format.

Hour 5

Stream

File Stream

File Stream is an abstract interface, there are many objects in Node that implement this interface.

The method to process the file stream is reading or writing the file stream.

To read or write a file stream, we need to import “fs” module before processing the file stream:

var fs = require("fs");

“fs” means the file system module.

“fs” module is used to read or write the file.

When a file stream is being read or written, four events may be triggered:

1. data event:   triggered when there is data to read.

2. end event:   triggered when there is no more data to read.

3. error event:   triggered when an error occurs.

4. finish event:   triggered when there is no more data to write.

Read Stream

The syntax to create an object to read a file stream is:

var obj = fs    . createReadStream('myfile. txt');

Example 5.1

1. Create an external file named “myfile. txt”, the content is:

“C#  IN  8  HOURS”

Save the file “myfile. txt” in the working folder “myNode”.

2. Create a main file named “readstream. js”, and save it in the working folder “myNode” too.

var fs = require("fs");     // import “fs” module

var data = 'Read the File Stream: ';      // initialize the data

var obj = fs.createReadStream('myfile.txt');

obj. setEncoding('utf8');    // reading & encoding with utf8

obj. on('data', function(datas) {   // bind data event to callback

data += datas;      // keep reading data

});

obj. on('end',function(){     // bind end event to callback

console. log(data);

});

obj. on('error', function(e){     // bind error event to callback

console. log(e. stack);     // show error messages

});

console    . log("An example of reading a file stream");

Output:

An example of reading a file stream

Read the File Stream: C# IN 8 HOURS

Explanation:

“require("fs");” imports “fs” module

“ fs.createReadStream('myfile.txt'); ” creates a reading stream object of the “myfile. txt”.

“obj. on(…)” binds an event to callback function. When an event is triggered, the callback function will be called.

“e. stack”: the error messages.

Write Stream

The syntax to create an object to write a file stream is:

var obj = fs    . createWriteStream('newfile. txt');

Example 5.2

1. Create a main file named “writestream. js”, and will save the file in the working folder “myNode”.

var fs = require("fs");     // import “fs” module

var data = 'Write the File Stream: GO IN 8 HOURS';   // contents

var obj = fs.createWriteStream('newfile.txt');

obj. write(data,'utf8');      // writing & encoding with utf8

obj. end();     // mark the end of the file

obj. on('finish', function() {   // bind finish event to callback

console. log("Finish Writing, please check newfile. txt");

});

obj. on('error', function(e){    // bind error event to callback

console. log(e. stack);     // show error message

});

console    . log("An example of writing a file stream");

2. Run “writestream. js”, and then check “newfile. txt”.

Output:

An example of writing a file stream

Finish Writing, please check newfile. txt

Explanation:

Please open the “newfile. txt”, you will find its new contents:

“Write the File Stream: GO IN 8 HOURS”

“require("fs");” imports “fs” module

“ fs. createWriteStream('newfile. txt');” creates a writing stream object of the “newfile. txt”.

“obj. end();” marks the end of the file.

“obj. on(…)” binds an event to callback function. When an event is triggered, the callback function will be called.

“e. stack”: the error messages.

Piping Stream

We can get data from one stream and pass it to another stream, which is called Piping Stream.

The syntax o Piping Stream is as follows:

readstream    . pipe(writestream);

Read the contents of one file and write them to another file.

Example 5.3

1. Create an external file named “infile. txt”, the content is:

“PHP  MYSQL IN  8  HOURS”

Save the file “infile. txt” in the working folder “myNode”.

2. Create a main file named “main. js”, and save it in the working folder “myNode” too.

var fs = require("fs");

// create an object of reading stream

var readstream = fs. createReadStream('infile. txt');

// create an object of writing stream

var writestream = fs. createWriteStream('outfile. txt');

// read the contents of the infile . txt & write to outfile . txt

readstream.pipe(writestream);

console. log("The example of piping stream. ");

console    . log("Please check the outfile. txt. ");

Output:

The example of piping stream.

Please check the outfile. txt.

Explanation:

Please open the “outfile. txt”, you will find its new contents:

“PHP MYSQL IN 8 HOURS”

“fs. createReadStream('infile. txt');” creates a reading stream object of the infile. txt.

“fs. createWriteStream('outfile. txt');” creates a writing stream object of the outfile. txt.

“readstream. pipe(writestream);” reads the contents of the infile. txt and then writes to outfile. txt.

__filename

“__filename” can get the name of the current file and its path.

Example 5.4

// create a file named “study . js”, its code is as follows :

console    . log( __filename );

Output:

C: \Users\RAY\myNode\study. js

Explanation:

“__filename” returns the name of the current file and its path.

__dirname

“__dirname” can get path and the directory name where the current file locates.

Example 5.5

// create a file named "learn . js", its code is as follows :

console    . log( __dirname );

Output:

C: \Users\RAY\myNode

Explanation:

“__dirname” returns the path and the directory name where the current file locates.

setTimeout()

“setTimeout()” creates a timer, and executes a specified function after several seconds.

setTimeout(function, time)

Example 5.6

function delay(){    // define a function

console. log( "Rust in 8 Hours! ");

}

console. log( "Show a message after 3 seconds: ");

setTimeout(delay, 3000);     // 3000 milliseconds

Output:

Show a message after 3 seconds:

Rust in 8 Hours!

Explanation:

“setTimeout(delay, 3000);” is a timer, executes the function “delay(){}” after 3000 milliseconds.

clearTimeout(t)

“clearTimeout(t)” clears the timer previously set up.

clearTimeout(t)

“t” is an object of the timer.

Example 5.7

function delay(){

console. log( "Rust in 8 Hours! ");

}

var t = setTimeout(delay, 3000);

clearTimeout(t);      // clear the above timer

console    . log("The timer has been cleared up! ");

Output:

The timer has been cleared up!

Explanation:

“clearTimeout(t)” clears the timer previously set up.

setInterval()

“setInterval()” creates a timer, and executes a specified function every other several seconds. Until press “ctrl+c” to stop running.

setInterval(function, time)

Example 5.8

function interval(){

console. log( "Keep running, until press ctrl+c");

}

// executes the above function every other 3 seconds

setInterval(interval, 3000);

Output:

Keep running, until press ctrl+c

Keep running, until press ctrl+c

Keep running, until press ctrl+c

……

Explanation:

“setInterval(interval, 3000);” is a timer, executes the function “interval(){}” every other 3000 milliseconds, until press “ctrl+c” to stop running.

Hour 6

File

Open a File

The syntax to open a file is as follows:

fs    . open(path/filename, mode, callback)

“fs” module is used to process files.

“mode” sets how to open a file, please see the following chart.

Mode

Description

r

Open the file in read mode.

An exception occurs if the file does not exist    .

r+

Open the file in read or write mode.

An exception occurs if the file does not exist    .

w

Open the file in write mode.

If the file does not exist, it will be created    .

w+

Open the file in write or read mode.

If the file does not exist, it will be created    .

a

Open the file in append mode.

If the file does not exist, it will be created    .

a+

Open the file in append or read mode.

If the file does not exist, it will be created    .

Example 6.1

// Please create a file “myfile . txt” in the working folder in advance .

var fs = require("fs");

console. log("A sample of opening a file. ");

fs.open('myfile.txt', 'r+', function(err) {

if (err) {

return console. error(err);

}

console. log("The file is opened successfully! ");

});

Output:

A sample of opening a file.

The file is opened successfully!

Explanation:

“fs. open(…)” open a file.

'myfile. txt' has been created in advance.

“r+” opens the file in read or write mode.

File Status

The syntax to obtain the status of a file is as follows:

fs    . stat(path/filename, callback);

Stats class has two important methods:

Stats. isFile() checks an item if it is a file.

Stats. isDirectory() checks an item if it is a directory.

Example 6.2

var fs = require("fs");

fs.stat('myfile.txt', function (err, stats) {

if (err) {

return console. error(err);

}

console. log("The file information was retrieved successfully! ");

console. log("This item is a file? " + stats.isFile() );

console. log("This item is a directory ? " + stats.isDirectory() );

});

Output:

The file information was retrieved successfully!

This item is a file? true

This item is a directory ? false

Explanation:

“fs. stat(…) {…}” obtains the information of the specified file.

“function (err, stats)” is a callback function. If the file doesn't exist, it will return some error messages.

“stats. isFile()” checks the “myfile. txt” if it is a file.

“stats. isDirectory()” checks the “myfile. txt” if it is a directory.

Write a File (1)

The syntax to write a file is as follows:

fs    . writeFileSync(file, data);

Write contents to a file synchronously

Example 6.3

var fs = require("fs");     // import “fs” module for writing files

fs.writeFileSync('syncfile.txt', 'Go in 8 Hours');

console. log("Write contents to a file successfully! ");

console    . log("Please check the syncfile. txt");

Output:

Write contents to a file successfully!

Please check the syncfile. txt

Explanation:

“require("fs")” imports “fs” module.

“fs” module is used to write or read a file.

“fs. writeFileSync('syncfile. txt', 'Go in 8 Hours');” writes the text “Go in 8 Hours” to the syncfile. txt synchronously.

Please open “syncfile. txt”, you can see its contents is “Go in 8 Hours”.

Read a File (1)

The syntax to read a file is as follows:

fs    . readFileSync(file)

Read the contents from a file synchronously

Example 6.4

var fs = require("fs");     // import “fs” module for reading files

var data = fs.readFileSync('syncfile.txt');

console. log("The contents of the syncfile. txt is: ");

console    . log(data. toString());

Output:

The contents of the syncfile. txt is:

Go in 8 Hours

Explanation:

“require("fs")” imports “fs” module.

“fs” module is used to write or read a file.

“var data = fs. readFileSync('syncfile. txt');” reads the contents from syncfile. txt synchronously.

“data. toString()” converts the data to a text string.

Write a File (2)

The syntax to write a file is as follows:

fs    . writeFile(file, data, callback)

Write contents to a file asynchronously

Example 6.5

var fs = require("fs");

fs.writeFile('asyncfile.txt', 'R in 8 Hours',  function(err) {

if (err) {

return console. error(err);

}

console. log("Write to a file successfully! ");

console. log("Please check the asyncfile. txt");

});

Output:      Write to a file successfully!

Please check the asyncfile. txt

Explanation:

“fs. writeFile('asyncfile. txt', 'R in 8 Hours',  function(err)” writes the data ”R in 8 Hours” to the file “asyncfile. txt” asynchronously. If an error occurs, the callback function will be called.

Please open asyncfile. txt, check its contents.

Read a File (2)

The syntax to read a file is as follows:

fs    . readFile(file, callback)

Read the contents from a file asynchronously

Example 6.6

var fs = require("fs");

fs.readFile ('asyncfile. txt', function (err, data) {

if (err) return console. error(err);

console. log("The content of the asyncfile. txt is: ");

console. log(data. toString());

});

Output:      The content of the asyncfile. txt is:

R in 8 Hours

Explanation:

“fs. readFile('asyncfile. txt', function (err, data)” reads the contents from asyncfile. txt asynchronously. If an error occurs, the callback function will be called.

“data. toString()” converts the data to a text string.

Close a File

The syntax to close a file is as follows:

fs    . close(fd, callback)

fd:   using fd. open().

callback:   a function will be called when an error occurs.

Example 6.7

var fs = require("fs");

var buf = new Buffer. alloc(1024);

fs. open('myfile. txt', 'w+', function(err, fd) {

if (err) {

return console. error(err);

}

console. log("myfile. txt is opened successfully! ");

fs.close(fd, function(err) {

if (err){

console. log(err);

}

console. log("myfile. txt is closed successfully! ");

});

});

Output:

myfile. txt is opened successfully!

myfile. txt is closed successfully!

Explanation:

“fs. close(fd, function(err)” closes a file “myfile. txt”.

Remove a File

The syntax to remove a file is as follows:

fs    . unlink(file. txt, callback)

Example 6.8

var fs = require("fs");

console. log("This is a sample to delete a file! ");

fs.unlink('myfile.txt', function(err) {

if (err) {

return console. error(err);

}

console. log("myfile. txt has been deleted successfully! ");

});

Output:

This is a sample to delete a file!

myfile. txt has been deleted successfully!

Explanation:

“fs. unlink('myfile. txt', function(err)” removes myfile. txt.

FS Methods

The following chart lists other frequently-used “fs” methods:

fs.access(file, mode, callback)

Check the permission of a specified file

fs.appendFile(filename, data, callback)

Append contents to a file

fs.chmod(file, mode, callback)

Change the permission of a file

fs.exists(file, callback)

Check whether the file exists

fs.link(path1, path2, callback(err))

Create a link between two paths

fs.truncate(file, length, callback)

Truncate the contents of a file

fs.utimes(file, access_time, modify_time, callback)

Modify the timestamp of a file

fs.watchFile(file, listener)

View the modification of a file

Hour 7

Operations

Create a Directory

The syntax to create a new directory is as follows:

fs    . mkdir(path, callback)

Example 7.1

var fs = require("fs");

console. log("Create a new directory 'newDir'");

fs.mkdir("/Users/Ray/myNode/newDir/",function(err) {

if (err) {

return console. error(err);

}

console. log("The directory 'newDir' is created successfully! ");

});

Output:

Create a new directory 'newDir'

The directory 'newDir' is created successfully!

Explanation:

“fs. mkdir("/Users/Ray/myNode/newDir/",function(err)” creates a new folder “newDir” in the working folder “myNode”.

Read a Directory

The syntax to read a directory is as follows:

fs    . readdir(path, function(err, files))

path: the directory and files that will be read.

files: all files in the path.

Example 7.2

// Please create three files a . txt, b . txt, c . txt, and put them

to the folder “newDir”

var fs = require("fs");

fs.readdir("/Users/Ray/myNode/newDir/",function(err, files) {

if (err) {

return console. error(err);

}

files. forEach( function (file){     // iterates through all files

console. log( file );      // display each file in the folder

});

});

Output:

a. txt

b. txt

c. txt

Explanation:

We can see there are three files in the directory “newDir”.

“fs. readdir("/Users/Ray/myNode/newDir/",function(err, files)” reads the directory “newDir”.

“function(err, files)” is a callback function, returns an error message or all files in the folder “newDir”.

“files. forEach( function (file)” iterates through all files in the folder “newDir”. “file” parameter represents each file.

Remove a Directory

The syntax to remove an empty directory is as follows:

fs    . rmdir(path, callback)     // remove empty folder only

Example 7.3

// Please delete the three files a . txt, b . txt, c . txt first .

var fs = require("fs");

console. log("The sample to remove a folder 'newDir'");

fs.rmdir("/Users/Ray/myNode/newDir/",function(err) {

if (err) {

return console. error(err);

}

console. log("The folder 'newDir' is removed successfully! ");

});

Output:       The sample to remove a folder 'newDir'

The folder 'newDir' is removed successfully!

Explanation:

“fs. rmdir("/Users/Ray/myNode/newDir/")” removes “newDir”.

Callbackify

“util. callbackify()” can call a callback function asynchronously.

“util” is a tool module, which contains many built-in functions such as a callback (), insptect(), isArray()….. etc.

The main function should be prefixed by a keyword “async”.

Let’s learn how to use “callbackify” function.

1. Define a main function by using “async” keywowd

async function mainFunction() {…}

2. Call the callback function by using callbackify();

const callbackFunction = util    . callbackify(mainFunction);

3. Define a callback function by using “=>” symbol

callbacFunction => {…}

Example 7.4

const util = require('util');    // import “util” module

async function mainFunction() {     // using “async”

return 'Ruby in 8 Hours';

}

const cbFunction = util.callbackify( mainFunction);   // call

cbFunction((err, data) => {     // define a callback function

if (err) throw err;

console. log(data);

});

Output:

Ruby in 8 Hours

Explanation:

“util” is a tool module, containing many built-in functions.

“async function mainFunction() {…}” defines a main function by using “async” keyword.

“const cbFunction = util. callbackify(mainFunction);” calls the callback function by using “callbackify()”.

“cbFunction((err, data) => {…}” defines a callback function by using “=>” symbol.

Inspect

“inspect(object)” can display the data of an object.

util    . inspect(object)

Example 7.5

var util = require('util');

function Book() {  //  "this" represents the Book object

this. title = 'Html';

this. when = 'in';

this. number = '8';

this. unit = 'Hours';

}

var obj = new Book();  // create a Book object & call Book

console    . log(util.inspect(obj) );

Output:

Book { title: 'Html', when: 'in', number: '8', unit: 'Hours' }

Explanation:      “this” represents the current object.

“util. inspect(obj)” returns the data of the Book object.

Inherits

The feature of a constructor can be inherited by another constructor.

The syntax to inherit a constructor is as follows:

util    . inherits(sub_constructor, super_constructor)

sub_constructor inherits all feature of a super_constructor.

Example 7.6

var util = require('util');     // import util module

function Super() {      // super constructor

this. value = "a + b";

a = 'Linux Shell';

b = ' in 8 Hours'

}

function Sub() {      // sub constructor

this. value = a + b;

}

util.inherits(Sub, Super);       // inheritance

var objSuper = new Super();

console. log(objSuper);

var objSub = new Sub();

console    . log(objSub);

Output:

Super { value: 'a + b' }

Sub { value: 'Linux Shell in 8 Hours' }

Explanation:

“function Super()” creates a super constructor.

“function Sub()” creates a sub constructor.

“this” represents the current object.

“util. inherits(Sub, Super);”: Sub constructor inherits all feature of the Super constructor.

“this. value = a + b;” in sub constructor: “this” means objSub, and

“a” value is “Linux Shell”.

“b” value is “ in 8 Hours”.

isArray

“isArray()” can check whether an object is an array.

var data = util    . isArray(object);

Example 7.7

var util = require('util');

var myArr = new Array;     // create an array “myArr”

var data1 = util.isArray (myArr);

console. log(data1);

var data2 = util.isArray (new Array);

console. log(data2);

var data3 = util.isArray ("Array");

console    . log(data3);

Output:

true

true

false

Explanation:

“isArray(object)” can check whether an object is an array.

isDate

“isDate()” can check whether an object is a date.

var data = util    . isDate(object);

Example 7.8

var util = require('util');

var data1 = util.isDate (new Date())

console. log(data1);

var data2 = util.isDate (Date())    // without new

console. log(data2);

var data3 = util.isDate ("12/20/2019")   // this is a string

console    . log(data3);

Output:

true

false

false

Explanation:

“isDate(object)” can check whether an object is a date.

isRegExp

“isRegExp()” can check whether an object is a Regular Expression.

var data = util    . isRegExp(object);

Example 7.9

var util = require('util');

var data1 = util.isRegExp (/Rust in 8 Hours/)

console. log(data1);

var data2 = util.isRegExp (new RegExp('string'))

console. log(data2);

var data3 = util.isRegExp (12/20/2019)

console    . log(data3);

Output:

true

true

false

Explanation:

“isRegExp(object)” can check whether an object is a regular expression.

Hour 8

Modules

OS Module

OS Module contains many operating system functions.

OS Module can get the information about the operating system.

var os = require("os");         // import os module

Example 8.1

var os = require("os");

console. log('The information of the current os is as follows: ');

// The host name is :

console. log('The host name is: ' + os.hostname() );

// The type of the operating system is :

console. log('The type of the operating system is: ' + os.type() );

// The platform is :

console. log('The platform is: ' + os.platform() );

// The total memory is :

console. log('The total memory is: ' + os.totalmem() + " bytes. ");

// The free memory is :

console. log('The free memory is: ' + os.freemem() + " bytes. ");

// The os version is :

console. log('The os version is: ' + os.release() + " version. ");

// The os runtime is :

console    . log('The os runtime is: ' + os.uptime() + " seconds. ");

Output:

The information of the current os is as follows:

The host name is: rayyao

The type of the operating system is: Windows_NT

The platform is: win32

The total memory is: 4181934080 bytes.

The free memory is: 2413699072 bytes.

The os version is: 6. 3. 9600 version.

The os runtime is: 15966 seconds.

Explanation:

“os. hostname()” returns the host name of the current os.

“os. type()” returns the type of the current os.

“os. platform()” returns the platform of the current os.

“os. totalmem()” returns the total memory of the machine.

“os. freemem()” returns the free memory of the machine.

“os. release()” returns the version of the os.

“os. uptime()” returns the run time of the machine.

Path Module

Path Module contains many small tools to process the file path.

var path = require("path");         // import path module

Example 8.2

var path = require('path') ;

console. log("The result to process path are as follows: ");

console. log("Join the path names: ");

console. log(path.join ('/app', 'ban', 'cat/egg', 'myfolder'));

// Output : \app\ban\cat\egg\myfolder

console. log("Search the first absolute path from left to right: ");

console. log(path.resolve ('/foo/bar', '/ray/baz'));

// Output : C : \ray\baz

console. log("Make the first absolute path from left to right: ");

console. log(path.resolve ('/foo/bar', 'baz'));

// Output : C : \foo\bar\baz

console. log("Check whether it is an absolute path: ");

console. log(path.isAbsolute ('/ray/baz'));

// Output : true

console. log("Convert to relative path: ");

console. log(path.relative ('/for/bar', '/ray/baz'));

// Output : .. \ .. \ray\baz

console. log("Return the last folder: ");

console. log(path.basename ('/for/bar/myfolder'));

// Output : myFolder

console. log("Return the extension name of a file: ");

console. log(path.extname ('/for/bar/myfolder/myfile. txt'));

// Output : . txt

console. log("Return the folder part, not include file: ");

console. log(path.dirname ('/for/bar/myfolder/myfile. txt'));

// Output : /for/bar/myfolder

Explanation:

“path. join()” joins the path names.

“path. resolve()” makes the first absolute path from left to right.

“path. isAbsolute()” checks whether it is an absolute path.

“path. relative()” converts the current path to a relative path.

“path. basename()” returns the last folder name.

“path. extname()” returns the extension name of the file.

“path. dirname()” returns folder names, not include file names.

DNS Module

DNS Module can interpret domain name.

var dns = require("dns")          // import “dns” module

The syntax to get an IP address from a website is as follows:

dns    . lookup(website, callback)

Example 8.3

var dns = require('dns');

dns.lookup('www.yahoo.com', function(err, address) {

console. log('The IP of www. yahoo. com: ', address);

if (err) {

console. log(err. stack);

}

});

Output:      The IP of www. yahoo. com:   72. 30. 35. 9

Explanation:

“dns. lookup('www. yahoo. com', function(err, address)” returns an IP address of the website “www. yahoo. com”.

The syntax to get a domain name from an IP address is:

dns    . reverse(address, callback)

Example 8.4

var dns = require('dns');

dns.reverse('72.30.35.9', function (err, domain_name) {

if (err) {

console. log(err. stack);

}

console. log("The domain name of 72. 30. 35. 9 is: ");

console. log(domain_name);

});

Output:

The domain name of 72. 30. 35. 9 is:

[ 'media-router-fp1. prod1. media. vip. bf1.yahoo.com ' ]

Explanation:

“dns. reverse('72. 30. 35. 9', function (err, domain_name)” returns a domain name of 72. 30. 35. 9.

The domain name is: yahoo. com

Domain Module

Domain Module can handle the error and exception.

var domain = require("domain")         // import a domain module

The syntax to create a domain object is as follows:

var domain_obj = domain    . create();

Example 8.5

var EventEmitter = require("events"). EventEmitter;

// import “events” module for event emitter

var domain = require("domain");    // import “domain” module

var domain_obj = domain.create();    // create a domain object

domain_obj. on('error', function(err){

console. log(err. message + " has been handled! ");

});

domain_obj. run(function(){

var emit_obj = new EventEmitter();     // create an object

emit_obj. emit('error',new Error(' The error')); // trigger error event

});

Output:

The error has been handled!

Explanation:

Domain Module can handle the error and exception.

“var EventEmitter = require("events"). EventEmitter;” imports “events” module for event emitter.

“var domain_obj = domain. create();”creates a domain object.

“domain_obj. on('error', function(err){…}” binds the error event to a callback function, when an error occurs, the callback function will be called.

“var emit_obj = new EventEmitter();” creates an EventEmitter object.

“emit_obj. emit('error',new Error());” triggers an error event.

Net Module

Net Module is a tool for networking communication.

The syntax to import the “net” module is as follows:

var net = require("net")

1. The syntax to create a server is as follows:

var server = net    . createServer(function(connection){});

“connection” parameter is used for client end.

Example 8.6

// Please open the first cmd window, create a server :

var net = require('net');

var server = net.createServer(function(connection) {

connection. write('Hello, Welcome to Server! \r\n');   // write data

console. log('A client has connected to the server! ');

});

server. listen(8080, function() {   // listening port 8080 for client

console. log('Server is listening…');

});

Output:

Server is listening…

Explanation:

“var server = net. createServer(function(connection)” creates a server and connect to the client end.

“connection. write();” writes data, will show data at the client end.

“server. listen(8080, function() {…}” is listening the port 8080, because the client end connects server through the port 8080.

2. The syntax to create client end is as follows:

var client = net    . connect({port: number}, function() {  }

{port number} is the code to connect the server and client end.

Example 8.7

//  Please open the second cmd window, create a client end .

//  Note : server and client end cannot use the same window .

var net = require('net');

var client = net.connect({port: 8080}, function() {

console. log('Connect to the server! ');

});

client. on('data', function(data) {    // bind ‘data’ event to callback

console. log(data. toString());   // show data from server

});

Output:

Connect to the server!

Hello, Welcome to Server!

Explanation:

“var client = net. connect({port: 8080}, function()” creates a client end and connects the server through port 8080.

“client. on('data', function(data)” receives the data from the server, and executes the callback function.

// Please check the server :

// Please check the client end :

Appendix

Test

01.

function fun(myFun, str) {

myFun(str);

}

fun( fill in (str){ console. log(str) }, "OK! " );

// anonymous function

A. fun

B. myFun

C. func

D. function

02.

// import event module

var events = require('events');

// create an event object

var eventObject = new events. fill in ();

A. event

B. Object

C. EventEmitter

D. EventObject

03.

buf = Buffer.alloc (8);

buf[0] = 104;

buf[1] = 101;

buf[2] = 108;

buf[3] = 108;

buf[4] = 111;

console. log( buf. fill in ('ascii'));       // read from buffer

A. toString

B. read

C. readFile

D. readFrom

04.

var data = 'Read the File Stream: ';

var obj = fs.createReadStream('myfile.txt');

obj. setEncoding('utf8');

obj. fill in ('data', function(datas) {  // bind an event to a listener

data += datas;

});

A. add

B. on

C. bind

D. require

05.

var fs = require("fs");

fs. fill in ('myfile. txt', function (err, callback) {

// get status of a file myfile . txt

if (err) {

return console. error(err);

}

A. status

B. statu

C. stats

D. stat

06.

var util = require('util');

function Book() {

this. title = 'Html';

this. when = 'in';

this. number = '8';

this. unit = 'Hours';

}

var obj = new Book();

console. log(util. fill in (obj));   // show data of the object

A. data

B. inspect

C. stat

D. callbackify

07.

console. log("Return the last folder: ");

console. log(path. fill in ('/for/bar/myfolder'));

// return the name of last folder .

A. lastname

B. foldername

C. basename

D. lastfolder

08.

// trigger Event001 event

eventObj. fill in ('Event001');

// trigger Event002 event

eventObj. fill in ('Event002');

A. trigger

B. emit

C. EventEmitter

D. Emitter

09.

const obj = Buffer. fill in ('RayYao');     // create a Buffer object

console. log(obj. toString('ascii '));

A. from

B. new

C. create

D. object

10.

var buf1 = Buffer. from(('Kotlin '));

var buf2 = Buffer. from(('in 8 Hours'));

var buf3 = Buffer. fill in ([buf1,buf2]);   // merge buffers

console. log("The buf3 is: " + buf3. toString());

A. merge

B. join

C. concat

D. connect

11.

var fs = require("fs");

var readstream = fs. createReadStream('infile. txt');

var writestream = fs. createWriteStream('outfile. txt');

readstream. fill in (writestream);    // piping stream

console. log("The example of piping stream. ");

console. log("Please check the outfile. txt. ");

A. piping

B. pipe

C. tubing

D. tube

12.

var fs = require("fs");

fs. fill in ('asyncfile. txt', 'R in 8 Hours',  function(err) {

// write contents to a file asynchronously

if (err) {

return console. error(err);

}

console. log("Write to a file successfully! ");

console. log("Please check the asyncfile. txt");

});

A. writeFileAsync

B. write

C. writeSync

D. writeFile

13.

const cbFunction = util. fill in (mainFunction);

// call the callback function

cbFunction((err, data) => {

if (err) throw err;

console. log(data);

});

A. callback

B. callbackify

C. callify

D. backify

14.

var dns = require('dns');

dns. fill in ('www. yahoo. com', function(err, address) {

// get a IP address from a website

console. log('The IP of www. yahoo. com: ', address);

if (err) {

console. log(err. stack);

}

});

A. ip

B. address

C. lookup

D. http

15.

fill in (function() {        // this is a delay function

eventObj. emit('delayEvent');

}, 6000);

A.   delay

B. callback

C. timeoutSet

D. setTimeout

16.

const buf = Buffer. fill in (6);

// create an unsafe buffer

console. log(buf);

A. allocUnsafe

B. fromUnsafe

C. buffUnsafe

D. objUnsafe

17.

const buf = Buffer.from('string');

console.log(buf[ fill in ]);     // get a ascii code of the string

A. ascii

B. string

C. index

D. character

18.

function interval(){

console. log( "Keep running, until press ctrl+c");

}

// executes the above function every other 3 seconds

fill in (interval, 3000);

A. setTimeout

B. setInterval

C. timoutSet

D. intervalSet

19.

var fs = require("fs");

console. log("This is a sample to delete a file! ");

fs. fill in ('myfile. txt', function(err) {      // remove a file

if (err) {

return console. error(err);

}

A. remove

B. delete

C. erase

D. unlink

20.

var util = require('util');

var data = util. fill in (/Rust in 8 Hours/)

// check whether an object is a regular expression .

console. log(data);

A. isRegularExpression

B. isRegExp

C. ReguarExpression

D. RegExp

21.

var dns = require('dns');

dns. fill in ('72. 30. 35. 9', function (err, domain_name) {

// get a domain name form the ip

if (err) {

console. log(err. stack);

}

console. log(domain_name);

});

A. domain

B. name

C. domainName

D. reverse

Node.js Source code download link:

https : //forms . aweber . com/form/12/162246712 . htm

Answers

01 .   D

08 .   B

15 .   D

02 .   C

09 .   A

16 .   A

03 .   A

10 .   C

17 .   C

04 .   B

11 .   B

18 .   B

05 .   D

12 .   D

19 .   D

06 .   B

13 .   B

20 .   B

07 .   C

14 .   C

21 .   D

Source Code Download

Node.js Source code download link:

https : //forms . aweber . com/form/12/162246712 . htm

Django

Hour 1

Introduction

Django Introduction

What is Django?

Django is an open source web application framework written in Python using the framework pattern of MVC, namely model M, view V, and controller C. It was originally developed to manage some news-focused websites of Lawrence publishing's, namely it is a CMS, released under the BSD license in July 2005. The framework is named after Django Reinhardt, a Belgian gypsy jazz guitarist.

Who is suitable for reading this book?

The people who know the Python programming.

The people who want to create web applications and build websites.

The beginners who want to become a Django programmer.

Install Django

Because Django was written in Python, you should install Python first before install Django.

Download Python

Free download Python-3. 7. 1 installer at:

https : //www . python . org/downloads/

Install Python

When the download finishes, run the installer by double-clicking it. Install Python to your local computer, check “Add Python 3.7 to PATH ”.

Then click “Customize installation ” into next step.

Click “next”.

Customize install location as ”C:\Python37 ”, then click “Install”.

Finally, you can see that the Python installation was successful.

Run Python

Please click “Start > Programs > Python3. 7 > IDLE (Python GUI)”.

Or

Click “Start > Programs > Python3. 7 > Python (Command Line)”.

You will see Python prompt:

>>>

Test Python Program

print( )

“print ( )” is used to print text or string to the screen.

For example

>>> print ("Hello World! ")

Output:   Hello World!

For example

>>> print ("Python is a very good language! ")

Output: Python is a very good language!

Download Django

https : //www . djangoproject . com/download/

On the right side of the download web page, please click the “Latest Release: Django-2.1.3.tar.gz ”, download the Django to your local computer, and unzip the software “Django-2 . 1 . 3 . tar . gz ” in current folder.

After you unzip the software, you can see a folder name “Django-2. 1. 3”. Please copy “Django-2. 1. 3” folder and its contents to C:\.

Now make sure that there are “Python37” folder and “Django-2. 1. 3” folder under C: \ root directory.

And make sure that there is a file “setup. py” under “Django-2. 1. 3” folder.

Under the C: \Django-2. 1. 3, you can see the file “setup. py”.

Install Django

Open a command prompt with “cmd ” command, input following commands:

Explanation:

“cd\ ” returns to C:\ root directory.

“cd django-2.1.3 ” goes to the folder “django-2. 1. 3”.

“python setup.py install ” installs the Django to your computer.

When installation is finished, you can see something like this:

Congratulation! Django is installed successfully!

Test Django

Open a command prompt with “cmd ” command, input following commands:

C: \Django-2. 1. 3>python

>>> import django

>>> print django. get_version( )

Output:

2. 1. 3

Explanation:

The output shows the “2. 1. 3”, which is the installed Django version. That means the Django installation is successful!

Hour 2

Basics

Creating Project

django-admin startproject myProject

“django-admin startproject myProject” can create a project.

Example 2.1

Open a command prompt window with “cmd ” command, input following commands:

C: \...... \cd\

C: \>cd Django-2. 1. 3

C: \Django-2. 1. 3>md myFolder

C: \Django-2. 1. 3>cd myFolder

C    : \Django-2. 1. 3\myFolder>django-admin startproject myProject

Explanation:

“C: \...... \cd\” goes back to the C: \ root directory.

“C: \>cd Django-2. 1. 3”  goes to the folder “Django-2. 1. 3”

“md myFolder” creates a folder “myFolder”.

“cd myFolder” goes to the folder “myFolder”

“django-admin startproject myPorject” creates a project “myProject”

Project Structure

If you want to know the structure of the project, open a command prompt with “cmd ” command, and input following commands:

Example 2.2

C: \>cd \Django-2. 1. 3\myFolder\myProject

C    : \Django-2. 1. 3\myFolder\myProject>dir

Output:

Explanation:

The structure of the myProject looks like this:

myProject/

|-- myProject

|      |-- __init__. py

|      |-- settings. py

|      |-- urls. py

|      |-- wsgi. py

|-- manage    . py

There are one file “manage. py” and one sub folder “myProject”.

“manage. py” is used to manage the project.

Sub folder “myProject” includes four files.

“_init_. py” is used to declare a module.

“settings. py” is used to configure the project.

“urls. py” is used to configure the url of the project.

“wsgi. py” is used to connect the application and web server.

Start up Server

python manage    . py runserver 0. 0. 0. 0: 8000

“python manage. py runserver 0. 0. 0. 0: 8000” can start up the server.

Now we can start up the server:

Example 2.3

C: \>cd Django-2. 1. 3\myFolder\myProject

C    : \Django-2. 1. 3\myFolder\myProject>python manage.py runserver 0.0.0.0:8000

Explanation:

IP 0. 0. 0. 0 allows other computers to connect to the development server, the default server port is 8000.

Preview Web Page

Open a browser, and enter your server IP and port number:

Example 2.4

http : //127 . 0 . 0 . 1 : 8000

Output:

Congratulations! The first project of Django runs successfully!

Next step we will configure the project, and make the web page have a perfect view.

Note:

1. Make sure that the server has been started up before you open the browser to view the output. Using “python manage. py runserver 0. 0. 0. 0: 8000” can start up the server.

2. Using the browser with http : //127 . 0 . 0 . 1 : 8000 can view the output.

Create a View File

Open the Python editor(IDLE), create a new file named “view.py ”, and write code as follows:

Example 2.5

from django. http import HttpResponse

def greeting(request):

return HttpResponse("Hi, My Friend     ! How are you! ")

Save the file to the following folder:       C: \Django2. 1. 3\myFolder\myProject\myProject.

And name the file as “view. py”.

Create an URL File

Open the Python editor(IDLE), create a new file named “urls.py ”, and write code as follows:

Example 2.6

from django. conf. urls import url

from . import view

urlpatterns = [

url(r'^$', view. greeting),

]

Save the file to the following folder:       C: \Django2. 1. 3\myFolder\myProject\myProject.

And name the file as “urls. py”, this new file should replace the original file “urls. py” in the same folder.

View the Web Page

Start up the server, open a browser, and enter your server IP and port number:

Example 2.7

http : //127 . 0 . 0 . 1 : 8000

Output:

Congratulations! This project has been completed successfully!

Template

A template is a text that separates the presentation and content of a document.

Example 2.8

We will create a template in C: \Django2. 1. 3\myFolder\myProject\templates,

the template file name is “greeting. html”.

myProject/

|-- myProject

|        |-- __init__. py

|        |-- settings. py

|        |-- urls. py

|        |-- view. py

|        |-- wsgi. py

|-- manage. py

|-- templates

|--     greeting.html

The code of the “greeting.html ” is as follows:

<h1>{{ greeting }}</h1>

Template Path

We need to tell the path of the template file to Django, please modify myProject/ setting. py, and change the DIRS in TEMPLATES to [BASE_DIR+"/ TEMPLATES ",], as shown below:

C: \Django-2. 1. 3\myFolder\myProject\myProject\setting. py

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',

],

},

},

]

Save the file. “ 'DIRS': [BASE_DIR+"/templates",], ” is a new setting in the file “setting. py”.

Modify view . py

We are now modifying view.py to add a new object for submitting data to the template.

C: \Django-2. 1. 3\myFolder\myProject\myProject\view. py

Example 2.9

#from django. http import HttpResponse

from django. shortcuts import render

def greeting(request):

context = {}

context['greeting'] = 'Hello! This is a template sample! '

return     render (request, 'greeting. html', context)

Explanation:

In the above example, we're using “render” to replace the HttpResponse. “render” also uses a context as the parameter. The key value of the context “greeting” corresponds to the variable "{{greeting }}}" in the template.

The “greeting” value is 'Hello! This is a template sample! '.

View the Web Page

Start up the server, open a browser, and enter your server IP and port number:

Example 2.10

http : //127 . 0 . 0 . 1 : 8000

Output:

Hour 3

Django Tags

Django Template Tags

There are a lot of built-in template tags in Django for programmers to use.

When you create a template file, you can use the template tags.

For example, in here we can edit the template file “greeting.html ” by using the template tags.

Now please open the template file “greeting.html ” to try the template tags.

If/Endif Tag

{% if condition %}

……

{% endif %}

Run the code based on the condition.

Example 3.1

{% if greeting == 'Hello! This is a template sample! ' %}

<h1>Django template is fun! </h1>

{%     endif %}

Note:

1. Make sure that the server has been started up before you open the browser to view the output. Using “python manage. py runserver 0. 0. 0. 0: 8000” can start up the server.

2. Using the browser with http : //127 . 0 . 0 . 1 : 8000 can view the output.

Output:

Django template is fun!

Elif/Endif Tag

{% if condition1 %}

……

{% elif condiiton2 %}

……

{% else %}

……

{% endif %}

Run the code based on the various conditions,

Example 3.2

{% if greeting == 'I am a template'  %}

<h1>Django template is fun! </h1>

{% elif greeting == 'Hello! This is a template sample! ' %}

<h1><i>AngularJS in 8 Hours! </i></h1>

{% else %}

<h1>Good! </h1>

{%     endif %}

Output:

AngularJS in 8 Hours

For Tag

{% for X in Y %}

......

{% endfor %}

for tag can iterate over a sequence.

Tthe loop syntax is for X in Y, X is the name of the variable used in each particular loop, and Y is the sequence to iterate.

Example 3.3

First, let’s modify the “view.py ” by writing the following code:

C: \Django-2. 1. 3\myFolder\myProject\myProject\view. py

#from django. http import HttpResponse

from django. shortcuts import render

def greeting(request):

week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

return render(request, "greeting    . html", { "week" : week})

Please save the file “view. py”.

Second, modify the “greeting.html ” by writing the following code:

C: \Django-2. 1. 3\myFolder\myProject\templates\greeting.

{% for days in week %}

{{days}}

{% endfor %}

Please save the file “greeting. html”

Third, open a browser with url: http : //127 . 0 . 0 . 1 : 8000

Output:

Mon Tue Wed Thu Fri Sat Sun

Comment Tag

{# This is a comment    . #}

The comment tag of Django is {# #} . The interpreter of Django will ignore the comments.

Example 3.4

{# The following is a For Tag example #}

{% for days in week %}

{{days}}

{% endfor %}

Output:

Mon Tue Wed Thu Fri Sat Sun

Include Tag

{% include "myFile    . html" %}

Include another html file to current template file.

Example 3.5

(1) Create an external file “myFile.html ”

C: \Django-2. 1. 3\myFolder\myProject\templates\myFile. html

<h2> Java in 8 Hours </h2>

Save the “myFile. html” in the template folder.

(2) Modify the “greeting.html ” by writing the following code:

C: \Django-2. 1. 3\myFolder\myProject\templates\greeting. html

{% include "myFile. html" %}

{% for days in week %}

{{days}}

{% endfor %}

Save the “greeting. html” in the template folder.

(3) Open a browser with url: http : //127 . 0 . 0 . 1 : 8000

Output:

Java in 8 Hours

Mon Tue Wed Thu Fri Sat Sun

Convert to Lower Case

{{ variable|lower }}

{{ variable|lower }} can convert the upper case to lower case.

Example 3.6

{# modify the greeting . html #}

{% for days in week %}

{{ days|lower }}

{% endfor %}

Please open a browser with url: http : //127 . 0 . 0 . 1 : 8000

Output:

mon tue wed thu fri sat sun

Convert to Upper Case

{{ variable|upper }}

{{ variable|upper }} can convert the lower case to upper case.

Example 3.7

{# modify the greeting . html #}

{% for days in week %}

{{ days|upper }}

{% endfor %}

Please open a browser with url: http : //127 . 0 . 0 . 1 : 8000

Output:

MON TUE WED THU FRI SAT SUN

String Length

{{ string | length }}

{{ string | length }} returns each string length.

Example 3.8

{# modify the greeting . html #}

{% for days in week %}

{{ days|length }}

{% endfor %}

Please open a browser with url: http : //127 . 0 . 0 . 1 : 8000

Output:

3 3 3 3 3 3 3

Truncating Tag

{{ string | truncatewords    : "number" }}

{{ string | truncatewords: "number" }} can truncate the string before the number. So you only see the words before the number.

Example 3.9

First, modify the “view.py ” by writing the code as follows:

C: \Django-2. 1. 3\myFolder\myProject\myProject\view. py

#from django. http import HttpResponse

from django. shortcuts import render

def greeting(request):

context = {}

context['greeting'] = 'Hello! This is a template sample! '

return render(request, 'greeting    . html', context)

Please save the file “view. py”.

Second, modify the “greeting.html ” by writing the following code:

C: \Django-2. 1. 3\myFolder\myProject\templates\greeting. html

{% if greeting == 'Hello! This is a template sample! ' %}

{{ greeting|truncatewords:"3" }}

{% endif %}

Please save the file “greeting. html”

Third, open a browser with url: http : //127 . 0 . 0 . 1 : 8000

Output:

Hello! This is ...

Explanation:

The original string is 'Hello! This is a template sample! '.

Now you only see three words appearing.

Block & Extend Tag

{% block name %}

“{% block name %}” defines a block.

{% extends "another    . html" %}

“{% extends "another. html" %}” extends another html file.

Example 3.10

Create Another.html

First, let’s create an html file named “another.html ” like this:

C: \Django-2. 1. 3\myFolder\myProject\templates\another. html

<h3> This is a block. </h3>

{% block myBlock %}

<p>Here will be replaced. </p>

{%     endblock %}

Save “another. html” in the folder “template”.

Modify Greeting.html

Second, modify the file “greeting.html ”;

C: \Django-2. 1. 3\myFolder\myProject\templates\greeting. html

{% extends "another. html" %}

{% block myBlock %}

<h3>Extend Successfully! </h3>

{% endblock %}

Save the “greeting. html” in the template folder.

View the Result

Third, Start up the server, open a browser with url: http : //127 . 0 . 0 . 1 : 8000

Output:

This is a block.

Extend Successfully!

Hour 4

Models

Models

The Django model is database dependent, and database-specific code is generally written in model. py. Django supports databases such as PostgreSQL, MySQL, SQLite, and Oracle etc.

SQLite3 is the default database in Django web applications. In this section we will introduce SQLite3 as an example.

Create an App

python manage    . py startapp myApp

“python manage. py startapp myApp” can create an app.

Example 4.1

Open the command line window with “cmd” command and input following command:

C: \ > cd\

C: \> cd \Django-2. 1. 3\myFolder\myProject

C    : \Django-2. 1. 3\myFolder\myProject\python manage.py startapp myApp

After the myApp has been set up, the directory looks like this:

myProject

|-- myApp

|     |-- __init__. py

|     |-- admin. py

|     |-- models. py

|     |-- tests. py

|     |-- views. py

|     |-- apps. py

|-- manage. py

|-- db    . sqlite3

Modify the models . py

In order to use myApp, we need to modify the models.py.

C: \Djanog-2. 1. 3\myFolder\myProject\myApp/models. py:

Example 4.2

# models. py

from django. db import models

class myDataBase(models. Model):

name = models    . CharField(max_length=20)

“myDataBase” is a name of this database. “name” is the field name of the table. “CharField” is the varchar. “max_length” is the maxmum length of the field name.

Modify the setting . py

We need to tell Djano that an App has been installed and modify the setting. py.

C: \Djanog-2. 1. 3\myFolder\myProject\myProject\setting. py

Example 4.3

INSTALLED_APPS = [

'django. contrib. admin',

'django. contrib. auth',

'django. contrib. contenttypes',

'django. contrib. sessions',

'django. contrib. messages',

'django. contrib. staticfiles',

'myApp ',     # add this item

]

We have added an item “myApp” in the setting. py.

Create a Data Table

Open the command line window with “cmd” and run the following commands to create a data table.

Example 4.4

C : \ > cd\

C : \> cd \Django-2 . 1 . 3\myFolder\myProject

C : \Django-2 . 1 . 3\myFolder\myProject\python manage . py migrate

C : \Django-2 . 1 . 3\myFolder\myProject\python manage . py makemigrations myApp

C : \Django-2 . 1 . 3\myFolder\myProject\python manage . py migrate myApp

Explanation:

python manage. py migrate

# Get ready for data table structure

python manage. py makemigrations myApp

# Let Django know that the updated model

python manage. py migrate myApp

# Create a data table structure for myApp

Modify urls . py

Modify the urls.py so that a database test file can be found by Django.

C: \Djanog-2. 1. 3\myFolder\myProject\myProject\urls. py

Example 4.5

from django. conf. urls import *

from . import view,testdb

urlpatterns = [

url(r'^testdb$', testdb. testdb),

]

testdb. py is a file that is used to add some data to the data table.

Create a file testdb . py

The functionality of the testdb.py is just like the INSERT in SQL.

C: \Djanog-2. 1. 3\myFolder\myProject\myProject\testdb. py

Example 4.6

from django. http import HttpResponse

from myApp. models import myDataBase

def testdb(request):

db = myDataBase(name='R in 8 Hours' )

db. save()

return HttpResponse("Data added is    : R in 8 Hours")

“R in 8 Hours ” has been added to the database.

Test Database

Example 4.7

Start up the server, visit http : //127 . 0 . 0 . 1 : 8000/testdb , you can see the message of data added successfully.

Output:

Retrieve Data

list = MyDataBase. objects. all()

# all() is equivalent to SELECT * FROM in SQL

result = MyDataBase. objects. filter(id=1)

# filter is equivalent to WHERE in SQL

result = MyDataBase. objects. get(id=1)

# returns a single object

The above commands can get the data from the database. Please edit the testdb. py.

Example 4.8

C: \Django-2. 1. 3\myFolder\myProject\myProject\testdb. py

from django. http import HttpResponse

from myApp. models import myDataBase

# get the data

def testdb(request):

list = myDataBase.objects.all()

result = ""

for var in list:

result = var. name + " "

return HttpResponse("<p>" + result + "</p>")

Start up the server, browse with url: http : //127 . 0 . 0 . 1 : 8000/testdb

Output:

R in 8 Hours

Explanation:

Because a data “R in 8 Hours” has been added previously, now the output should be “R in Hours”.

Update the Data

If you want to update the data table, please use following command:

Example 4.9

C: \Django-2. 1. 3\myFolder\myProject\myProject\testdb. py

from django. http import HttpResponse

from myApp. models import myDataBase

# update the data

def testdb(request):

db = myDataBase(name='C# in 8 Hours')

db. save()

return HttpResponse(db    . name)

Start up the server, browse with url: http : //127 . 0 . 0 . 1 : 8000/testdb

Output:

C# in 8 Hours

Delete the Data

If you want to delete a data in data table, please use delete() and following command:

Example 4.10

C: \Django-2. 1. 3\myFolder\myProject\myProject\testdb. py

from django. http import HttpResponse

from myApp. models import myDataBase

# delete data

def testdb(request):

myDataBase. objects. all().delete()

return HttpResponse("<p>Delete Successfully    . </p>")

Start up the server, browse with url: http : //127 . 0 . 0 . 1 : 8000/testdb

Output:

Delete Successfully

Hour 5

Form/Method

Django Form

HTML forms are a classic feature of web interactivity. This chapter will show you how to handle the data from the user-submitted form with Django.

The HTTP protocol works by "request-reply" mode when a client sends a request; it can attach data to the request. The server can parse the request to get the data from the client, respond the user and provide a specific service based on the URL.

Get Method

Example 5.1

Create Search.py

We will create a file “search. py” to receive user requests.

C: \Django-2. 1. 3\myFolder\myProject\myProject\search. py

from django. http import HttpResponse

from django. shortcuts import render_to_response

# form

def myForm(request):

return render_to_response('myForm. html')

# receive the requesting data

def search(request):

if 'str' in request.GET:

text = 'The search text is: ' + request.GET ['str']

else:

text = 'You have submitted an empty form. '

return HttpResponse(text)

Create myForm.html

Then, we create a form “myForm. html” for user input.

C: \Django-2. 1. 3\myFolder\myProject\templates\myForm. html

<html>

<body>

<form action="/search" method="get">

<input type="text" name="str">

<input type="submit" value="search">

</form>

</body>

</html>

Modify Urls.py

Finally, we modify the urls.py to tell the path to Django.

C: \Django-2. 1. 3\myFolder\myProject\myProject\urls. py

from django. conf. urls import url

from . import view,testdb,search

urlpatterns = [

url(r'^greeting$', view. greeting),

url(r'^testdb$', testdb. testdb),

url(r'^myForm$', search. myForm),

url(r'^search$', search. search),

]

Test the Form

Example 5.2

Start up the server, visit http : //127 . 0 . 0 . 1 : 8000/myForm , and input “JQuery in 8 Hours” into the text field:

Output:

After clicking the “search” button, you can see the following output:

Output:

Calculation

We can use Get( ) method to calculate math problems.

Example 5.3

Create a Project

Open the command line window with “cmd”, input the following commands:

C: \>cd\

C: \>cd \Django-2. 1. 3\myFolder

C: \Django-2. 1. 3\myFolder

django-admin startproject Calculation

cd calculation

python manage    . py startapp Calculating

In the above commands, we create a project “Calculation” first, then we create an app “Calculating” under the project.

Now the structure of this project looks like this:

Calculation/

├──　Calculating

│ 　    　　├──　__init__. py

│ 　    　　├──　admin. py

│ 　    　　├──　apps. py

│ 　    　　├──　models. py

│　    　 　├──　tests. py

│ 　    　　└──　views. py

├──　manage    . py

Modify The Views.py File.

C: \Django-2. 1. 3\myFolder\Calculation\Calculating\views. py

from django. shortcuts import render

from django. http import HttpResponse

def add(request):

x = request. GET['x']

y = request. GET['y']

z = int(x)+int(y)

return HttpResponse(str(z))

Modify The Urls.py File.

C: \Django-2. 1. 3\myFolder\Calculation\Calculation\urls. py

from django. conf. urls import url

from django. contrib import admin

from Calculating import views as calculating_views

urlpatterns = [

url(r'^add/$', calculating_views. add, name='add'),

url(r'^admin/', admin. site. urls),

]

Start up the server, open a browser with the following url: http : //127 . 0 . 0 . 1 : 8000/add/?x=100&y=200

Output:

Explanation:

The url has the parameters “x=100” and “y=200”, therefore, the web page output is 300.

Post Method

POST methods are more commonly used when submitting data.

We'll use this method next and use a URL and handler to display the view and process the request at the same time

Example 5.4

Create myPost.html

We will create a file “myPost. html” in the folder “template”. This form is used to receive the input from users.

C: \Django-2. 1. 3\myFolder\myProject\templates\myPost. html

<html>

<body>

<form action="/postMethod" method="post">

{% csrf_token %}

<input type="text" name="str">

<input type="submit" value="Submit">

</form>

Your search text is:   <b>{{ message }}</b>

</body>

</html>

{% csrf_token %} is used to prevent the forger submit of a request. CSRF means that Cross Site Request Forgery.

Create Find.py

Then we create the find. py file and use the postMethod function to process the POST request.

C: \Django-2. 1. 3\myFolder\myProject\myProject\find. py

from django. shortcuts import render

from django. views. decorators import csrf

# receive post requesting data

def postMethod(request):

var ={}

if request.POST:

var['message'] = request.POST ['str']

return render(request, "myPost    . html", var)

The above code uses the Post method.

Modify urls.py

Finally, we will modify the urls. py to tell the path to the Django.

C: \Django-2. 1. 3\myFolder\myProject\myProject\urls. py

from django. conf. urls import url

from . import view,testdb,search, find

urlpatterns = [

url(r'^greeting$', view. greeting),

url(r'^testdb$', testdb. testdb),

url(r'^myForm$', search. myForm),

url(r'^search$', search. search),

url(r'^postMethod$', find. postMethod),

]

Test the Form

Example 5.5

Start up the server, visit http : //127 . 0 . 0 . 1 : 8000/postMethod , and input “C# in 8 Hours” into the text field:

Output:

Please click the “Submit” button.

Output:

Redirection

Sometimes we want to redirect the user's current page to another page.

redirect("https    : //www. xxxxxxxx. com")

Example 5.6

Create Redirect.py

We create a file “redirect. py”in the:

C: \Django-2. 1. 3\myFolder\myProject\myProject\redirect. py

#redirection

from django. shortcuts import render, redirect

def visit(request):

return     redirect ("http: //www. google. com")

The above code will redirect to Google page.

Modify Urls.py

Modify the “urls. py” to let Django know about the new file “redirect. py”.

from django. conf. urls import url

from . import view,testdb,search,find,redirect

from django. contrib import admin

urlpatterns = [

url(r'^greeting$', view. greeting),

url(r'^testdb$', testdb. testdb),

url(r'^myForm$', search. myForm),

url(r'^search$', search. search),

url(r'^postMethod$', find. postMethod),

url(r'^admin/', admin. site. urls),

url(r'^visit$', redirect.visit),

]

View the Result

Start up the server, open the browser with the link:

http : //127 . 0 . 0 . 1 : 8000/visit

The above link will redirect to www . google . com .

Output:

Hour 6

Administration Tool

Administration Tools

Django provides web-based management tool. Its automatic management tool is part of django. contrib.  You can see it on INSTALLED_APPS in the project's settings. py.

View Setting.py

C: \Django-2. 1. 3\myFolder\myProject\myProject\settings. py

INSTALLED_APPS = (

'django. contrib. admin',

'django. contrib. auth',

'django. contrib. contenttypes',

'django. contrib. sessions',

'django. contrib. messages',

'django. contrib. staticfiles',

)

Django. contrib is a huge function collection, which is a part of Django basic code.

Activation of Management Tools

We can set up the urls. py to activate the Management Tools.

Example 6.1

C: \Django-2. 1. 3\myFolder\myProject\myProject\urls. py

from django. conf. urls import url

from . import view,testdb,search, find

from django.contrib import admin

urlpatterns = [

url(r'^greeting$', view. greeting),

url(r'^testdb$', testdb. testdb),

url(r'^myForm$', search. myForm),

url(r'^search$', search. search),

url(r'^postMethod$', find. postMethod),

url(r'^admin/', admin.site.urls),

]

“from Django. contrib import admin” imports the administration tools.

“url(r'^admin/', admin.site.urls)” sets up a url to use admin tools.

When the above file urls. py is configured, the Django administration tools can start to run.

Start up the server, and open the browser with url: http : //127 . 0 . 0 . 1 : 8000/admin/ ,

Output:

Create a Super User

python manage    . py createsuperuser

“Python manages. py createsuperuser” can create a super user.

Example 6.2

C: \Django-2. 1. 3\myFolder\myProject>python manage.py createsuperuser

Username (leave blank to use 'root'): admin

Email address: admin@in8hours. com

Password:

Password (again):

Superuser created successfully    .

The password is set as 12345.

Start up the server, and open the browser with url: http : //127 . 0 . 0 . 1 : 8000/admin/

Output:

Please input the user name “admin” and password “12345”, and login the site of administration.

Manage Database

In order to manage the database, we need to register the database to “admin” first and modify the “admin. py” file.

Example 6.3

C: \Django-2. 1. 3\myFolder\myProject\myApp\admin. py

from django. contrib import admin

from myApp. models import myDataBase

# Register your database here .

admin.site.register(myDataBase)

Open the browser with url: http : //127 . 0 . 0 . 1 : 8000/admin/ ,

Output:

Another Database

We can create more databases. Because the functionality of the administration tools is so powerful that it can manage many databases at the same time.

Modify the models . py

To create one more database, we need to modify the models. py.

Example 6.4

C: \Django-2. 1. 3\myFolder\myProject\myApp\models. py

# models. py

from django. db import models

class myDataBase(models. Model):

name = models. CharField(max_length=20)

class newDataBase (models. Model):

username   = models. CharField(max_length=200)

age    = models. IntegerField(default=0)

email  = models    . EmailField()

In here, we create a database named “newDatabase ”.

Register the New Database

Then, we need to register the “newDatabase” to “admin” by modifying the “admin. py” file.

Example 6.5

C: \Django-2. 1. 3\myFolder\myProject\myApp\admin. py

from django. contrib import admin

from myApp. models import myDataBase,newDataBase

# Register your models here .

admin.site.register([myDataBase, newDataBase])

Open the browser with url: http : //127 . 0 . 0 . 1 : 8000/admin/ ,

Output:

We can see another database “newDatabase” has been set up successfully.

Back-End Sample

Django can be powerful if we add less code in the back end,.

The back-end code is always related to the admin. py file in each app.

Example 6.6

1. Create A Project

C : \Django-2 . 1 . 3\myFolder>django-admin startproject myBlog

2. Create A App

C : \Django-2 . 1 . 3\myFolder> cd myBlog

C : \Django-2 . 1 . 3\myFolder\myBlog>python manage . py startapp Blog

3. Modify the Models.py

C: \Django-2. 1. 3\myFolder\myBlog\Blog\models. py

from django. db import models

class Essay(models. Model):

title = models. CharField(u'Titile', max_length=256)

content = models. TextField(u'Content')

pub_date = models. DateTimeField(u'Publish Time', auto_now_add=True, editable = True)

update_time = models    . DateTimeField(u'Update Time',auto_now=True, null=True)

4. Add Blog to Settings.pys

Add the blog to INSTALLED_APPS in settings. py.

C: \Django-2. 1. 3\myFolder\myBlog\myBlog\settings. py

INSTALLED_APPS = (

'django. contrib. admin',

'django. contrib. auth',

'django. contrib. contenttypes',

'django. contrib. sessions',

'django. contrib. messages',

'django. contrib. staticfiles',

'Blog' ,       # add this item

)

5. Synchronize All Data Tables

Open the command line window with cmd command:

C : \Django-2 . 1 . 3\myFolder\myBlog>python manage . py makemigrations

C : \Django-2 . 1 . 3\myFolder\myBlog>python manage . py migrate

Output:

After input above commands, you can see the output:

……

Creating table django_content_type

Creating table django_session

Creating table blog_article

6. Create an Account

python manage    . py createsuperuser

“Python manages. py createsuperuser” can create a super user.

C: \Django-2. 1. 3\myFolder\myBlog>python manage.py createsuperuser

Username (leave blank to use 'root'): admin

Email address: admin@in8hours. com

Password:

Password (again):

Superuser created successfully    .

The password is set as 12345.

7. Register the Blog

Enter the Blog folder and modify the admin. py file.

C: \Django-2. 1. 3\myFolder\myBlog\Blog\admin. py

from django. contrib import admin

from . models import Essay

admin.site.register(Essay)

8. View the Results

Open the browser with url: http : //127 . 0 . 0 . 1 : 8000/admin/ ,

Output:

You can click the Essay to manage the database.

Appendix 1

Python Basic

What is Python?

Python is a general-purpose, object-oriented and open source computer programming language, it is a high-level, human-readable and a corresponding set of software tools and libraries.

Download Python

Free download Python installer at:

https : //www . python . org/downloads/

Install Python

When the download finishes, run the installer by double-clicking it. Install Python to your local computer, For example: at C:\Python35. Click “Next”.

Make sure to select the option “Add Python. exe to Path”.

Please complete the installation of Python.

Run Python

Please click “Start > Programs > Python3. 5 > IDLE (Python GUI)”.

Or click “Start > Programs > Python3. 5 > Python (Command Line)”.

You will see Python prompt:

>>>

First Python Program

print( )

“print ( )” is used to print text or string to the screen.

Example 1.1

>>> print ("Hello World! ")

Output:   Hello World!

Example 1.2

>>> print ("Python is a very good language! ")

Output: Python is a very good language!

>>> print ("Learn Python in 8 Hours! ")

Output:   Learn Python in 8 hours.

Explanation:

“>>> ” is a Python primary prompt.

“print ( )” displays the text.

The Shell Prompt

>>>

“>>> ” is the Python interactive command shell prompt, requests the input from the user.

For example:

>>> 10 + 8

18

>>> 100 - 2

98

>>> " Hello " + " World! "

' Hello  World! '

>>> " Very Good! " * 3

' Very Good    !   Very Good!   Very Good! '

Explanation:

“>>> ” prompts that you can input data, and press Enter.

The lines without >>> are responded by Python.

For example:

>>> 100 * 2

200

>>> 72 / 9

8

>>> ( 2 + 3 ) * 4

20

>>> 10 % 3

1

>>> 2 ** 3

8

Explanation:

*

multiplication

/

division

%

remainder

**

exponentiation

Configure Editor

In order to run the whole Python program instead line by line, or easily copy or paste whole code, you need to configure the python editor.

Please click “Start > All Programs > Python3. 5 > IDLE (Python GUI)”.

Click “Option > Configure IDLE > General > Open Edit Window” > OK.

After selecting “Open Edit Window”, you can run the whole Python program instead line by line. Press “F5 ” key to run the program.

(Run>Run Module)

Note:

Option “Open Edit Window” runs the program by whole code.

Execute the whole program by pressing F5 key.

(Run>Run Module)

Option “Open Shell Window” runs the program line by line.

Execute the one line code by pressing Enter key.

Variables

A “variable” is a container that stores a data value. The variable value may change when program is running.

variableName = value

variableName1 = variableName2 = value

variableName1,  variableName2 = value1, value2

“variableName” is a variable name.

Example 1.3

var = 100

var1 = var2 = var3 = 100

var1, var2, var3 = 100, 200, 300

Explanation:

“var = 100” defines a variable named “var”, whose value is 100.

“var1 = var2 = var3 = 100” assigns the value “100” to “var1”, var2”, “var3”.

“var1, var2, var3 = 100, 200, 300” respectively assigns the value “100, 200,300” to “var1”, var2”, “var3”.

Variables & Comment

A variable's value can be used in Python programs.

variableName = value

print (variableName)

# Symbol can be used in a comment.

# comment

Example 1.4

var01 = 100

print (var01)       # Output : 100

Example 1.5

var02 = "Python is very good! "

print (var02)       # Output : Python is very good !

Explanation:

“print ( )” is used to display content.

# is a symbol of comment.

“# Output : 100” is a comment.

“# Output : Python is very good ! ” is a comment.

Arithmetic Operator

Operator

Operation

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Remainder

//

Integer Division

**

Exponentiation

Note:

“%” modulus operator divides the first operand by the second operand, returns the remainder.

“//” works like “/”, but returns an integer.

“**” returns the result of the first operand raised to the power of the second operand.

Example 1.6

a = 100 + 200

b = 72/ 9

c = 25 % 7

d = 7 // 3

e = 8 ** 2

print (a, b, c, d, e)

Output:

(300, 8, 4, 2, 64)

Explanation:

“100 + 200” returns 300

“72/9” returns 8

“25 % 7” returns 4.

“7 // 3” returns 2.

“8 ** 2” returns 64.

Assignment Operators

“x += y” equals “x = x + y”, please see the following chart:

Operators

Examples:

Equivalent:

+=

x+=y

x=x+y

- =

x - =y

x=x - y

* =

x * =y

x=x * y

/ =

x / =y

x=x / y

%=

x%=y

x=x%y

//=

x // =y

x=x // y

**=

x**=y

x=x**y

Example 1.7

x=20

y=2

x %= y

print (x)

Output:

0

Explanation:

“x %= y” equals  “x = x % y”

Example 1.8

m=100

n=18

m%= n

print (m)

Output:

10

Explanation:

“m %= n”  equals “m = m % n”.

Comparison Operators

Operators

Running

>

greater than

<

less than

>=

greater than or equal

<=

less than or equal

==

equal

! =

not equal

After using comparison operators, the result will be true or false.

Example 1.9

a=100

b=200

result1= (a> b)

print (result1)

result2= (a== b)

print (result2)

result3= (a!= b)

print (result3)

Output:

False

False

True

Explanation:

result = (a>b)    # test 100>200     outputs false .

result = (a==b)  # test 100==200  outputs false .

result = (a! =b)   # test 100 ! =200   outputs true .

Logical Operators

Operators

Equivalent

and

logical AND

or

logical OR

not

logical NOT

After using logical operators, the result will be True or False.

Example 1.10

x=True

y=False

a=x and y

print (a)

b=x or y

print (b)

c=not x

print (c)

Output:

False

True

False

Explanation:

True and True

returns true

True and False

returns False

False and False

returns False

True or True

returns True

True or False

returns True

False or False

returns False

not False

returns True

not True

returns False

Conditional Operator

The syntax of conditional operator looks like this:

(if-true-do-this)      if (test-expression)  else   (if-false-do-this)

( test-expression) looks like a<b, x! =y, m==n. etc.

Note: The syntax of the conditional operator in Python is different from the “ ? : “ ternary operator in C++ or Java.

Example 1.11

a=100

b=200

result = "apple" if (a<b) else "banana"

print (result)

Output:

apple

Explanation:

The conditional operator use (a<b) to test the “a” and “b”, because “a” is less than “b”, it is true. Therefore, the output is “apple”.

Convert Data Type

Function

Operation

int(x)

convert x to an integer number

str(x)

convert x to a string

chr(x)

convert x to a character

float(x)

convert x to a floating point number

hex(x)

convert x to a hexadecimal string

oct(x)

convert x to a an octal string

round(x)

round a floating-point number x .

type(x)

detect x data type

Example 1.12

num1 = int (8. 67)

print (num1)     # returns 8

num2 = round (8. 67)

print (num2)    # returns 9 . 0

num3 = float (5)

print (num3)        # returns 5 . 0

Explanation:

dataType(  ) can convert the data type of a value.

Triple Quotes

Triple Quotes are used to display multiple lines of text.

‘‘‘     ’’’

For example:

multiString = '''Python

is a very

good language! '''

print (multiString)

Output:

Python

is a very

good language!

Explanation:

The text included inside the triple quotes can cross over multilines.

Exercise : Ticket Fare

If…else…

Please click “Start > Programs > Python3. 5 > IDLE (Python GUI)”.

Write the following code to the IDLE editor:

age = 15

ticket = "Child Fare" if (age < 16 ) else "Adult Fare"

print (ticket)

Save the file, and run the program by pressing F5 key.

(Run>Run Module).

Output:

Child Fare

Explanation:

The conditional operator use (age < 16) to test the “age” and “16”, because “age” is less than “16”, it is true. Therefore, the output is “Child Fare”.

Summary

“print ( )” is used to print text or string to the screen.

“>>> ” is the Python interactive command shell prompt, requests the input from the user.

A “variable” is a container that stores a data value. The variable value may change when program is running.

variableName = value

# Symbol can be used in a comment.

“%” modulus operator divides the first operand by the second operand, returns the remainder.

“//” works like “/”, but returns an integer.

“**” returns the result of the first operand raised to the power of the second operand.

“x += y” equals “x = x + y”

Comparison operators: >, <, >=, <=, ==, ! =.

Logical operators: and, or, not.

Conditional operator:

(if-true-do-this)  if (test-expression)  else   (if-false-do-this)

int(x) converts x to an integer number.

Triple Quotes ‘‘‘  ’’’ are used to display multiple lines of text.

Appendix 2

Texts & Answers

Tests

Please choose the correct answer.

(1)

“Python manages. py fill in ” can create a super user.

A. createuser

B. createsuper

C. createusersuper

D. createsuperuser

(2)

“fill in myProject” can create a Django project.

A.   startproject

B. django startproject

C. django-admin startproject

D. django-manage startproject

(3)

{% if greeting == 'Hello! This is a template sample! ' %}

<h1>Django template is fun! </h1>

{%  fill in   %}

A. if        B. end         C. endif        D. ifend

(4)

“ fill in myApp” can create an app.

A. python admin. py startapp

B. python manage. py startapp

C. django admin. py startapp

D. django manage. py startapp

(5)

from django. http import HttpResponse

from django. shortcuts import render_to_response

# form

def myForm(request):

return render_to_response('myForm. html')

# receive the requesting data

def search(request):

if 'str' in  fill in . GET:

text = 'The search text is: ' + request. GET['str']

else:

text = 'You have submitted an empty form. '

A. request     B. demand     C. appeal     D. ask

(6)

Django provides web-based management tool. Its automatic management tool is part of django. contrib.  You can see it on INSTALLED_APPS in the project's settings. py file.

fill in = (

'django. contrib. admin',

'django. contrib. auth',

'django. contrib. contenttypes',

'django. contrib. sessions',

'django. contrib. messages',

'django. contrib. staticfiles',

)

A. INSTALL_APPLICATIONS

B. INSTALLED_APPPLICATIONS

C. INSTALL_APPS

D. INSTALLED_APPS

(7)

The structure of the myProject looks like this:

myProject/

|-- myProject

|      |-- __init__. py

|      |-- settings. py

|      |-- urls. py

|      |-- wsgi. py

|-- manage    . py

“fill in . py” is used to connect the application and web server.

A. _init_        B. settings        C. ursl        D. wsgi

(8)

{% for days fill in week %}

{{days}}

{% endfor %}

A. to        B. at        C. in        D. on

(9)

python manage. py migrate

# Get ready for data table structure

python manage. py makemigrations myApp

# Let Django know that the updated model

python manage. py fill in myApp

# Create a data table structure for myApp

A. create        B. migrate        C. table        D. structure

(10)

Before opening the browser with http : //127 . 0 . 0 . 1 : 8000 to view the Django result, we should start up the fill in .

A. printer        B. laptop        C. server        D. monitor

(11)

“from Django. contrib import admin” imports the administration tools.

“url(r'^admin/', admin. site. urls)” sets up a fill in to use adminstration tools.

A. Django        B. application        C. app        D. url

(12)

“python manage. py fill in 0. 0. 0. 0: 8000” can start up the server.

A. runserver        B. startserver        C. start        D. server

(13)

The comment tag of Django is fill in . The interpreter of Django will ignore the comments.

A. {{   }}        B. {#   #}        C. {%   %}        D. {?   ?}

(14)

list = MyDataBase. objects. all()

# all() is equivalent to SELECT * FROM in SQL

result = MyDataBase. objects. filter(id=1)

# filter is equivalent to WHERE in SQL

result = MyDataBase. objects. fill in (id=1)

# returns a single object

A. return        B. set        C. get        D. filter

(15)

from django. shortcuts import render

from django. views. decorators import csrf

# receive post requesting data

def postMethod(request):

var ={}

if fill in . POST:

var['message'] = request. POST['str']

return render(request, "myPost. html", var)

A. request     B. demand     C. appeal     D. ask

(16)

from django. contrib import admin

from myApp. models import myDataBase

# Register your database here .

admin. site. fill in (myDataBase)

A. sign up        B. login        C. enroll        D. register

(17)

fill in variable fill in can show the value of a variable.

A. ((      ))        B. {{      }}        C. [[      ]]        D. <<   >>

(18)

{{ string | fill in : "number" }} can truncate the string before the number.

A. truncateword

B. truncatetext

C. truncatewords

D. truncatetexts

(19)

# the following code will delete a data .

from django. http import HttpResponse

from myApp. models import myDataBase

def testdb(request):

myDataBase. objects. all(). fill in ()    # delete data

return HttpResponse("<p>Delete Successfully. </p>")

A. delete        B. remove      C. erase      D. expunge

(20)

# the following code will redirect to a new web site .

from django. shortcuts import render, redirect

def visit(request):

fill in ("http://www.google.com")

# redirection

A. redirection

B. redirect

C. return redirection

D. return redirect

---The End---

Answers

01    . D

11    . D

02    . C

12    . A

03    . C

13    . B

04    . B

14    . C

05    . A

15    . A

06    . D

16    . D

07    . D

17    . B

08    . C

18    . C

09    . B

19    . A

10    . C

20    . D

Note:

This book is suitable for the programmers who have Python knowledge previously .

Django Source code download link:

https : //forms . aweber . com/form/31/448508031 . htm

Source Code Download

Django Source code download link:

https : //forms . aweber . com/form/31/448508031 . htm

Scala

Hour 1

Introduction

What is Scala Language?

The Scala language is a general-purpose programming language that can be executed on the JVM and. net platforms for both large-scale application development and lightweight programming. It was developed by Martin Odersk in 2001. Scala is widely used for its elegant type-safe programming scheme.

Scala is a pure object-oriented language with OO features, but it's also a functional language that allows you to write code with functional ideas.

Scala is built on top of the JVM and interoperates seamlessly with Java.

The great advantage of Scala: The Scala language is scalable, allowing you to write both small scripts and complex server-side programs.

The Feature of Scala

Scala is a pure object-oriented programming language

- Encapsulation/information hiding.

- Inheritance.

- Polymorphism/dynamic binding.

- All predefined types are objects.

- All operations are performed by sending messages to objects.

- All user-defined types are objects.

Scala is a functional programming language

- Higher-order functions

- Closures

- Pattern matching

- Single assignment

- Lazy evaluation

- Type inference

- Tail call optimization

- Type inference

Scala is very compatible and portable

- Scala executes on the JVM

- Scala can interoperate with JAVA

- Scala has the same platform portability as JAVA

Install JDK

Before  installing Scala, you must install Java JDK first.

About JDK (also called Java SE)

JDK (Java Development Kit) contains all Java class libraries, all tool building and running Java programs. JDK can create a Java development environment.

Download JDK

http : //oracle . com/download

or

http : //www . oracle . com/technetwork/java/javase/downloads/index . html

Please click the link to download the newest version JDK at Oracle website. (Figure 1)

(Figure 1   Download JDK at Oracle Website)

If your computer is a 32-bit operating system, download the JDK with x86; If your computer is a 64-bit operating system, download the JDK with x64. (Figure 2)

(Figure 2)

Install the JDK

Please install the newest version of the JDK to your computer. For example, install Java SE 12.0.1.

After installing the Java SE 12. 0. 1, please check the directory:

C: \Program Files\Java\jdk-12. 0. 1

You can find the “jdk-12.0.1 ” in there.

Please remember the installation path and jdk version.

Configure Java Environment Variables

The following chart is the configure parameters:

Variable Name

JAVA_HOME

Variable Value

C : \Program Files\Java\jdk-12 . 0 . 1

Variable Name

Path

Variable Value

; %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin ;

1. Please click  Control Panel > System > Advanced System Settings > Environment Variables

2. Click “ New… ”

3. Input “JAVA_HOME”.

4. Input “C: \Program Files\Java\jdk-12. 0. 1”. As follows:

5. Click “OK ”

6. Select “Path”.

7. Click “Edit… ”

8. Append “ ; %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin; ”

As follows:

( Note: If in Windows 10, you need to add the variable values one by one as follows: )

9. Click “OK ”, and restart the computer.

Test Java Environment

"Start" > " Run" > type "cmd ". Go to “C: \Users\YourName”.

Type “Java  -version ” as follows

Congratulation! The JDK has been installed successfully!

Install Scala

Download the Scala

https : //www . scala-lang . org/download/

Click Scala-2.12.8.msi.

Install the Scala

Please install scala-2.12.8 in C: \Program Files (x86)\scala.

And remember the directory:

C: \Program Files (x86)\scala

Configure Scala Environment Variables

The following chart is the configure parameters:

Variable Name

SCALA_HOME

Variable Value

C : \Program Files (x86)\scala

Variable Name

Path

Variable Value

; %SCALA_HOME%\bin;%SCALA_HOME%\jre\bin ;

Variable Name

Classpath

Variable Value

. ; %SCALA_HOME%\bin ;

Note: the method of the configure Scala environment variables is the same as the method of the configure Java environment variables.

Click “New…”

Click “OK” , and restart the computer.

Test Scala Environment

"Start" > " Run" > type "cmd ". Go to “C: \Users\YourName”.

Type “scala  -version ” as follows

Congratulation! The Scala has been installed successfully!

Hour 2

Basics

“Hello World” Program

Working Folder

Please go to C: \Users\YourName, create a folder “myScala ”. Now the working folder is “C: \Users\YourName\myScala ”, which is used to save Scala files.

Example 2.1

Please open the Windows NotePad, write the following code in it.

object HelloWorld {

def main(args: Array[String]) {

println("Hello, world!")

}

}

Save the file as “HelloWorld. scala” in the working folder “myScala”.

"Start" > " Run" > type "cmd ". Go to “C: \Users\YourName\myScala”. Type “scala HelloWorld. scala”, run the program

Output:

Hello world!

Explanation:

“object HelloWorld” means that the object name is “HelloWorld”

Note: The file name of the Scala file should be the same as object name.

The Scala extension name is “. scala”.

The Scala files should be saved in the working folder “myScala”

“def main(args: Array[String])” is the main function that is always executed first.

“args: Array[String]” is the argument which is used to accept the input of the string.

“println( )” outputs the contents.

“scala  HelloWorld. scala” is a command to run the HelloWorld program.

Basic Grammar

- Case-sensitive

Scala is a case-sensitive language.

For example: Hello and hello is different.

- Class name

The first letter of all class names should be capitalized.

For example: HelloWorld

- File name & Object name

The file name should be the same as object name.

For example: HelloWorld. scala  &  object HelloWorld

- Method names

All method names start with a lowercase letter.

For example: def myMethod( )

- Semicolon (;)

A semicolon is used to end a line of statement.

For example: println(“Hello”);

Scala Keywords

Scala keywords are reserved by Scala Language. We cannot use the following keywords as variables, constants, or function names.

abstract

case

catch

class

def

do

else

extends

false

final

finally

for

forSome

if

implicit

import

lazy

match

new

null

object

override

package

private

protected

return

sealed

super

this

throw

trait

try

true

type

val

var

while

with

yield

-

:

=

=>

<-

< :

<%

> :

#

@

Scala Comment

/*….. */  is a symbol for multi-line comment

//   is a symbol for single-line comment

Example 2.2

object HelloWorld {

/*

* Here is a hello-world program

* Here is a Scala program sample

*/

def main(args: Array[String]) {

println("Hello, world! ")    // output Hello, world !

}

}

Output:      Hello, world!

Explanation:

/*…*/ is used for multi-line comments

// is used in single-line comments

Package

A package is a code module that has some functionality, The Scala package provides specific functionality to the program.

Define a package:

package package_name

class class_name

For example:

package myPackage{     // define a package

class HelloWorld     // the content of the package

}

Import a package

import package_name

For example:

import java. awt. Color   // import Color package

Data Type

The data type of the Scala is the same as the data type of the Java.

Data Type

Description

Byte

8-bit signed integer

Short

16-bit signed integer

Int

32-bit signed integer

Long

64-bit signed integer

Float

32-bit floating point number

Double

64-bit floating point number

Char

16-bit unsigned unicode character

String

character series

Boolean

true or false

Unit

no value

Null

empty reference

Nothing

sub class of any other type

Any

super class of any other type

AnyRef

base class for all referenced classes

Int Type

For example:

100

88

Long Type

A long type number is followed by a L.

For example:

0868L

3000L

Float Type

A float type number is followed by an F.

For example:

2c60F

3. 14159F

Boolean Type

For example:

true

false

Character Type

Character types are defined by single quotes ‘ ’.

For example:

‘ a’

‘ B’

String Type

String Types are defined by double quotes “ ”.

For example:

“ Go in 8 Hours”

“ Rust in 8 Hours”

Multi-line String Type

Multi-line String Type are defined by treble quotes “““   ”””.

For example:

“““    Django in 8 Hours

& AngularJS in 8 Hours

are very good books    ”””

Null Type

Null type contains an empty value.

For example:

Scala. Null

Scala. Nothing

Escape Sequences

The “ \ ” backslash character can be used to escape characters.

\n outputs content to the next new line.

\r makes a return

\t makes a tab

\’ outputs a single quotation mark.

\” outputs a double quotation mark.

For example:

println("Hello, \t\t\t World! " )    // Output :   Hello,      Would !

Hour 3

Operators

Variables

Variable: the value of which may change while the program is running. The syntax to define a variable is as follows:

var variable_name =  value

Example 3.1

object Var000 {

def main(args: Array[String]) {

var myVar = 100      // define a variable

print(myVar)

}

}

Output:

100

Explanation:

“var myVar = 100” define a variable “myVar”, its value is 100.

Declare Variable Type

The syntax of declaring a variable type is as follows:

var variable     : type = value

Example 3.2

object Var001 {

def main(args: Array[String]){

var myVar1:Int = 1000         // define Int variable

var myVar2:String = " Good "      // define String variable

print(myVar1)

print(myVar2)

}

}

Output:       1000  Good

Explanation:

“var myVar1: Int = 1000” define an Int type variable.

“var myVar2: String = " Good "” define a String variable.

Declare Multi Variables

The syntax to declare multi variables are as follows:

var variable1, variable2, variable3 = value

Example 3.3

object Var002 {

def main(args: Array[String]){

var var1, var2, var3 = 10000;       // define multi variables

println(var1);

println(var2);

println(var3)

}

}

Output:

10000

10000

10000

Explanation:

“var var1, var2, var3 = 10000;” defines multi variables.

Constants

Constant: the value of which cannot change while the program is running. There are two formats to define a constant as follows:

val Constant_Name = value

val Constant_Name     : type =  value

Example 3.4

object Val002 {

def main(args: Array[String]){

val Con1 = "C# in "     // define a constant

val Con2 : Int = 8         // define a constant

val Con3 : String = " Hours"     // define a constant

print(Con1 + Con2 + Con3);

}

}

Output:

C#  in  8 Hours

Explanation:

The first letter of a constant name should be capitalized.

Arithmetical Operators

Operators

Running

+

add or connect strings

-

subtract

*

multiply

/

divide

%

get modulus

% modulus operator divides the first operand by the second operand, returns the remainder. e. g. 4%2, the remainder is 0.

Example 3.5

object Arith000 {

def main(args: Array[String]) {

var add=100 + 200;   println (add);   // output 300

Var div=800 / 2;   println (div);   // output 400

var mod=10 % 3;   println ( mod );    // output 1

}

}

Output:

300

400

1

Explanation:

+

add or connect strings

/

divide

%

get modulus

Comparison Operators

Operators

Running

Returns

>

greater than

true or false

<

less than

true or false

>=

greater than or equal

true or false

<=

less than or equal

true or false

==

equal

true or false

! =

not equal

true or false

Example 3.6

object com000 {

def main(args: Array[String]) {

var x = 200; var y = 100;

println( x == y );    // output false

println( x ! = y );       //  output true

println( x > y );         //  output true

println( x <= y );     // output false

}

}

Output:

false

true

true

false

Explanation:

>

greater than

<

less than

>=

greater than or equal

<=

less than or equal

==

equal

! =

not equal

Logical Operators

Operators

Equivalent

Returns

&&

and

true or false

||

or

true or false

!

not

true or false

Example 3.7

object log000 {

def main(args: Array[String]) {

var x=true; var y=false;

var a = x && y;   println ( a );

var b = x || y;   println ( b );

var c = ! x;   println ( c );

}

}

Output:

false

true

flase

Explanation:

true && true;

returns true;

true && false;

returns false;

false &&false;

returns false;

true II true;

returns true;

true II false;

returns true;

false II false;

return false;

! false;

returns true;

! true;

returns false;

Assignment Operators

Operators

Examples:

Equivalent:

+=

x+=y

x=x+y

-=

x-=y

x=x-y

*=

x*=y

x=x*y

/=

x/=y

x=x/y

%=

x%=y

x=x%y

Example 3.8

object log000 {

def main(args: Array[String]) {

var x=90;   var y=2;

x+=y;  println ( x );

x/=y;   println ( x );

x%=y;  println ( x );

x-=y;   println ( x );

}

}

Output:

92

46

0

-2

Explanation:

x+=y

is equal to  x=x+y

x-=y

is equal to  x=x-y

x%=y

is equal to  x=x%y

x/=y

is equal to  x=x/y

Hour 4

Statement

If Statement

if ( test-expression ) {       // if true do this;    }

“if statement” executes codes inside { … } only if a specified condition is true, does not execute any codes inside {…} if the condition is false.

Example 4.1

object If000 {

def main(args: Array[String]) {

var a=200;

var b=100;

if (a>b) {   // if true, do this

print ( "a is greater than b" );

}}}

Output:

a is greater than b

Explanation:

( a>b ) is a test expression, namely (200>100), if returns true, it will execute the codes inside the { }, if returns false, it will not execute the codes  inside the { }.

If-else Statement

if ( test-expression) {   // if true do this;    }

else  {   // if false do this;    }

“if... else statement” runs some code if a condition is true and runs another code if the condition is false

Example 4.2

object Ifelse001 {

def main(args: Array[String]) {

var a=100; var b=200;

if (a>b) {print ("a is greater than b. ")}

else { print ( "a is less than b" );}      // do this

}}

Output:

a is less than b

Explanation:

( a>b ) is a test expression, namely (100>200), if returns true, it will output  ”a is greater than b. ” if returns false, it will output “a is less than b”.

If…else if…else

“If…else if…else” is a multi-test expression.

if ( test expression ){

//  if true, do this

} else if ( test expression ){

//  if true, do this

} else if ( test expression ){

//  if true, do this

} else {

//  if true, do this

}

Example 4.3

object IfStatement {

def main(args: Array[String]) {

var x = 200;

if ( x == 100 ){

println("The value of x is 100");

}else if ( x == 200 ){    // if true , do this

println("The value of x is 200");

}else if ( x == 300 ){

println("The value of x is 300");

}else {

println("Do know the value of X");

}}}

Output:

The value of x is 200

Explanation:

Because the precondition is “var x = 200;”, therefore the “if( x == 200 )” is true, then output the “The value of x is 200”.

While Loop

while ( test-expression ) {      // some code in here;   }

“while loop” loops through a block of code if the specified condition is true.

Example 4.4

object While000 {

def main(args: Array[String]) {

var counter = 0

while (counter < 8) {    // run 8 times

print ( "&" );

counter = counter + 1;

}

}

}

Output:

&&&&&&&&

Explanation:

“counter< 8” is a test expression, if the condition is true, the code will loop less than 8 times, until the counter is 8, then the condition is false, the code will stop running.

Do-While Loop

Do {     // some code in here } while ( test-expression);

“do... while” loops through a block of code once, and then repeats the loop if the specified condition is true.

Example 4.5

object Do000 {

def main(args: Array[String]) {

var counter = 0

do {

print ( "@" );

counter = counter +1;

} while (counter<8);      // run 8 times

}}

Output:

@@@@@@@@

Explanation:

“counter< 8” is a test expression, if the condition is true, the code will loop less than 8 times, until the counter is 8, then the condition is false, the code will stop running.

For Loop (1)

for( variable <    - number1 to number2) { // some code; }

“for( variable <- number1 to number2){}” runs the code block by the specified number of times from number1 to number 2.

Example 4.6

object For000 {

def main(args: Array[String]) {

var x = 0;

for( x <- 0 to 8) {    // run from 0 to 8 times

print( x );

}

}

}

Output:

012345678

Explanation:

“for( x <- 0 to 8)” runs the code from 0 to 8 times.

For Loop (2)

for( variable <    - number1 until number2) { // some code; }

“for( variable <- number1 until number2){}” runs the code block by the specified number of times from number1 until number 2.

Example 4.7

object For001 {

def main(args: Array[String]) {

var y = 0;

for( y <- 0 until 8) {   // run from 0 until 8 times

print( y );

}

}

}

Output:

01234567

Explanation:

“for( x <- 0 until 8)” runs the code from 0 until 8 times.

For Loop (3)

for( variable <    - List) { // some code; }

“for( variable <- List) { // some code; }” runs the block of code based on the values of the List.

Example 4.8

object For002 {

def main(args: Array[String]) {

var z = 0;

val myList = List(0,1,2,3,4,5);

for( z <- myList ){   // run the code based on the List

print( z );

}}}

Output:

012345

Explanation:

“for( z <- myList )” runs the code based on the values of the List.

Hour 5

Methods

Method

A method is a code block that can repeat to run many times. To define a method.

(1) The syntax to define a method is as follows:

def method_name( )    : return_type={……}

If the method has no return value, the return type can be Unit.

(2)To call a method, use “method_name ( );”

method_name ( );

Example 5.1

object Test {

def main(args: Array[String]) {

println( "The result is : " + mul(50,2) );   // call the method

}

def mul( x:Int, y:Int ) : Int = {   // define a method

var result: Int = 0

result = x * y

return result        // return value

}

}

Output:

The result is : 100

Explanation:

“def mul( x: Int, y: Int ) : Int = { } “ defines a method

“x: Int” specifies that the data type of x is Int.

“”mul(50,2) ); “ calls the method. 50 and 2 are parameters which are passed to x and y.

If the method has no return value, the return type can be specified as Unit , for example:   def method_name( ):Unit ={……}

Default Parameters

When defining a method, you can use the default parameters.

method_name( arg1=value1, arg2=value2)

Example 5.2

object Defa000 {

def main(args: Array[String]) {

println(mul() );   // call the method without parameters

}

def mul( a:Int=100, b:Int=2 ) : Int = {    // default parameters

var result: Int = 0

result = a * b

return result

}}

Output:

200

Explanation:

“a: Int=100, b: Int=2” are default parameters. When you call a method without using parameters, in this case, the default parameters will work.

Closure

Closure: the left part of the arrow is the parameter list, the right part of the arrow is the function body.

var variable = (parameters) => function body

Example 5.3

object Anony000 {

def main(args: Array[String]) {

println( "adds(1) value is " +  adds(1) )    // calling

println( "adds(2) value is " +  adds(2) )    // calling

}

var num = 100

val adds = (n:Int) => n + num     // define a closure

}

Output:

adds(1) value is 101

adds(2) value is 102

Explanation:

“val adds = (n: Int) => n + num” defines a closure.

(n: Int) is a parameter

“n + num” is a function body.

String

String is consisted of a series of characters, and it is always enclosed in double quotation marks.

A string is an immutable object, therefore the String object cannot be modified.   The syntax to create a string is as follows:

var string_name = "string_value";

or

var string_name     : String = "string_value";

Example 5.4

object Str000 {

val book = "Go in 8 Hours"     // create a string

def main(args: Array[String]) {

println( book )

}}

Output:

Go in 8 Hours

Explanation:

“val book = "Go in 8 Hours" ” creates a string.

String Length

The syntax to get the length of a string is as follows:

myString    . length()

Example 5.5

object Leng000 {

def main(args: Array[String]) {

var myString = "Rust in 8 Hours";

var leng = myString.length() ;    // get the length

println( "The string length is : " + leng );

}

}

Output:

The string length is : 15

Explanation:

“myString. length();” gets the length of the string.

String Connection

The syntaxes to connect two strings are as follows:

string1    . concat(string2);

string1 + string2 ;

Example 5.6

object Con000 {

def main(args: Array[String]) {

var str1 = "JAVA";

var str2 =  "C#";

var str3 =  "in 8 Hours: ";

println( str1.concat(str3) );    // connecting

println( str2 + str3 );      // connecting

}}

Output:      JAVA in 8 Hours

C# in 8 Hours

Explanation:

“str1. concat(str3) );” connects str1 with str3.

“str2+str3” connects str2 with str3.

String Functions

Frequently Used String Functions List

char charAt(int index)

Returns the character of the specified position

int compareTo(Object o)

Compare strings with objects

int compareTo(String anotherString)

Compare two strings in dictionary order

int compareToIgnoreCase(String str)

Compare two strings in dictionary order, regardless of case

String1 concat(String2 str)

Connects the specified string2 to the end of the string1

boolean contentEquals(StringBuffer sb)

Compares this string to the specified stringbuffer .

boolean endsWith(String suffix)

Tests whether this string ends with the specified suffix

boolean equals(Object anObject)

Compares this string to the specified object

int hashCode()

Returns the hash code for this string

int indexOf(int ch)

Returns the index of this string

int indexOf(String str)

Returns the index of the specified string at the first occurrence

String intern()

Returns a canonical representation of a string object

int lastIndexOf(int ch)

Returns the index of the specified character at the last occurrence

int lastIndexOf(String str)

Returns the index where the string appears on the right

int length()

Returns the length of this string

boolean matches(String regex)

Tells whether this string matches a given regular expression

String replace(char oldChar, char newChar)

Newchar replaces oldchar

String[] split(String regex)

Split this string according to the regular expression

boolean startsWith(String prefix)

Tests whether this string starts with the specified prefix

boolean startsWith(String prefix, int toffset)

Tests whether this string starts with the specified prefix .

String substring(int beginIndex)

Returns a new substring

String substring(int beginIndex, int endIndex)

Returns a substring

char[] toCharArray()

Convert a string to an array of characters

String toLowerCase()

Convert all characters in string to lowercase

String toString()

Returns a string

String toUpperCase()

Convert all characters in string to uppercase

String trim()

Removes the beginning and end blank of the string

Hour 6

Arrays

Array

An array is a particular variable, which can contain one or more values at a time.

(1) The first syntax to create an array is as follows:

val array_name = new Array[Type](length)

array-name(index0) = value0;

array-name(index1) = value1;

array-name(index2) = value2;

Example 6.1

val color =  new Array[String](3)       // create an array

color(0) = "Red";        // assign value

color(1) = "Blue";

color(2) = "Green"

Explanation:

Above code creates an array, array name is “color”, and it has three elements: color (0), color (1), color (2). Its indexes are 0, 1, and 2. Its values are red, blue, and green.

Note: The index of the first element is 0, and the index of the last element is “array. length -1”.

(2) The second syntax to create an array as follows:

val array_name = Array (“value0”, “value1”, “value2”);

The  syntax to access an array element is as follows:

array_name(index)

Note: The index of the first array element is 0.

Example 6.2

object Arr000 {

def main(args: Array[String]) {

var color = Array("Red", "Blue", "Green")   // create an array

print( color(0) )    // access the first array element

}}

Output:

Red

Explanation:

“Array("Red", "Blue", "Green")” creates an array with three elements. “color(0)” accesses the first array element.

Access Array Elements

The syntax to access all elements of the array is as follows:

for ( each_element <    - array_name ) { }

Example 6.3

object Acc000 {

def main(args: Array[String]) {

var myArray = Array(0. 1, 0. 2, 0. 3, 0. 4, 0. 5)

for ( num <- 　myArray ) {    // access all elements

println( num )

}

// Calculate the sum of all elements of an array

var sum = 0. 0;

for ( n <- 0 to (myArray.length - 1)) {  // access elements

sum += myArray(n);

}

println("The sum is " + sum);

}

}

Output:

0. 1

0. 2

0. 3

0. 4

0. 5

The sum is 1. 5

Explanation:

“for ( num <- 　myArray ) {    }” accesses all elements.

“myArray. length-1” accesses the last element of the array.

Connect Array

The syntax to connect two arrays is as follows:

concat( array1, array2)

Befor using concat(), you need to import Array. _ tool.

Example 6.4

import Array._           // import array tools for concat()

object Merge000 {

def main(args: Array[String]) {

var array1 = Array(0. 1, 0. 2, 0. 3)

var array2 = Array(0. 4, 0. 5, 0. 6)

var array3 = concat( array1, array2)   // connect two arrays

for ( elements <- array3 ) {

println( elements )

}}}

Output:

0. 1

0. 2

0. 3

0. 4

0. 5

0. 6

Explanation:

Before using concat(), you need to import Array. _ tool.

“concat( array1, array2)” connects two arrays

Reverse Array Elements

The syntax to reverse all elements of an array is as follows:

array    . reverse. toBuffer

Before using array function, you need to import Array. _ package

Example 6.5

import Array. _

object Rev000 {

def main(args: Array[String]) {

var myArray = Array(0, 1, 2, 3, 4)

for (a: Int <- myArray.reverse.toBuffer ){     // reverse elements

print(a + "  ")

}}}

Output:

4  3  2  1  0

Explanation:

“myArray. reverse. toBuffer){  }” reverses elements of the array.

Array Operations

ArrayBuffer is a mutable object, which can be changed during program running.

The syntax to create an ArrayBuffter is as follows:

val arr = ArrayBuffer[Int]()

Before using ArrayBuffer, you need to import scala. collection. mutable. ArrayBuffer

The functions handling list:

arr += element   // append an element at the end of the array

arr ++= Array()   // appends another array at the end of the array

arr . trimEnd(n )     // remove last elements  of the array

arr . insert(index, elements)   // insert elements at the specified index

ar    r . remove(index, elements)   // remove elements at the specified index

Example 6.6

import scala. collection. mutable. ArrayBuffer

import Array. _

object Arr008 {

def main(args: Array[String]) {

val arr = ArrayBuffer[Int]()  // create an empty array

arr += 10  // append an element at the end

// now the element is 10

arr += (11,12,13)  // append multi elements

// now the elements are 10 11 12 13

arr ++= Array(14,15,16)   // append another array

// now the elements are 10 11 12 13 14 15 16

arr. trimEnd(2)   // remove last two elements

// now the elements are 10 11 12 13 14

arr. insert(2,100, 200)  // insert elements at index 2

// now the elements are 10 11 100 200 12 13 14

arr. remove(4,2)   // remove elements at index 4

// now the elements are 10 11 100 200 14

for (myArray: Int <- arr){  // output all elements

print(myArray + "  ")

}}}

Output:

10  11  100  200  14

Explanation:

See the function-handling list on the above.

Array Sort

The syntax to sort an array is as follows:

array    . sorted. toBuffer

Example 6.7

object Sort003{

def main(args: Array[String]) {

val arr = Array(5, 3, 1, 4, 2, 0)

val sortArr = arr.sorted.toBuffer      // sort the array

for (myArray: Int <- sortArr){   // output all elements

print(myArray + "  ")

}

}

}

Output:

0  1  2  3  4  5

Explanation:

“arr. sorted. toBuffer” sorts the array.

Before sorted,  the sequence of the elements is: 5,3,1,4,2,0

After sorted, the sequence of the elements is: 0,1,2,3,4,5

Hour 7

Collection

Scala List

List is an immutable object, which cannot be changed during program running. List can store duplicated objects.

The syntax to define a list is as follows:

val list_name    : List[Type] = List(val1, val2, val3, …)

The operation of List is as follows:

list_name. head   // returns the first element of the list

list_name. last   // returns the last element of the list

list_name. tail   // returns a list except the first element

list_name    . isEmpty   // returns true when the list is empty

Example 7.1

object Color000 {

def main(args: Array[String]) {

val colors = List("Red", "Yellow", "Green")

val color0 = List()

println( "The first color is: " + colors.head )

println( "The last color is: " + colors.last )

println( "The tail color is: " + colors.tail )

println( "The color0 list is empty ? " + color0.isEmpty )

}

}

Output:

The first color is Red.

The last color is Green

The tail color is List(“Yellow”, “Green”)

The color0 is empty? true

Explanation:

list_name. head   // returns the first element of the list

list_name. last   // returns the last element of the list

list_name. tail   // returns a list except the first element

list_name. isEmpty   // returns true when the list is empty

Connect Two Lists

The syntax to connect two lists are as follows:

List1     ::: List2

or

List    . concat (List1, List2)

A new List will return after two lists are connected.

Example 7.2

object conlist000 {

def main(args: Array[String]) {

val title1 = List("Java", "in")

val title2 = List("Ruby", "in")

val title3 = List("8", "Hours")

println(title1 ::: title3 )     // connect two lists

println(List.concat(title2, title3) )   // connect two lists

}

}

Output:

List(“Java”, “in”, “8”, Hours)

List(“Ruby”, “in”, “8”, Hours)

Explanation:

“title1 ::: title3” connects two lists, returns a new list.

“List. concat(title2, title3)” connects two lists, returns a new list.

Scala Set

A Scala Set is a collection of non-repeating objects, all elements of which are unique.

The syntax to create a Set is as follows:

val set_name = Set(val1, val2, val3,…)

The operation of List is as follows:

set_name. head   // returns the first element of the set

set_name. last   // returns the last element of the set

set_name. tail   // returns a set except the first element

set_name    . isEmpty   // returns true when the set is empty

Example 7.3

object Set000 {

def main(args: Array[String]) {

val pets = Set("Tiger", "Lion", "Bear")

val pet0 = Set()       // define an empty Set

println( "The first pet is: " + pets. head )

println( "The last pet is: " + pets. last )

println( "The tail pet is: " + pets. tail )

println( "The pet0 Set is empty ? " + pet0. isEmpty )

}}

Output:

The first pet is Tiger.

The last pet is Bear

The tail pet is List(“Lion”, “Bear”)

The pet0 is empty? true

Explanation:

set_name. head   // returns the first element of the set

set_name. last   // returns the last element of the set

set_name. tail   // returns a set except the first element

set_name. isEmpty   // returns true when the set is empty

Set Operations

Some operating functions of Set are as follows:

set1 ++ set2     // connect two Sets, returns a disorder Set

set. max     // get the maximum value in the Set

set    . min      // get the minimum value in the Set

Example 7.4

object Test {

def main(args: Array[String]) {

val set1 = Set(0,1,2,3,4,5)

val set2 = Set(6,7,8,9)

var set3 = set1 ++ set2

println("The connected Set is : " )

println(set3)

println( "The minimum element is : " + set3. min )

println( "The maximum element is : " + set3. max )

}}

Output:

The connected Set is :

Set(0, 5, 1, 6, 9, 2, 7, 3, 8, 4)

The minimum element is : 0

The maximum element is : 9

Explanation:

set1 ++ set2     // connect two Sets, returns a disorder Set

set. max     // get the maximum value in the Set

set. min      // get the minimum value in the Set

Scala Map

Map is a collection of key/value structures, all its values can be obtained by its key, the key in the Map is unique.

The syntax to create a Map is as follows:

val Map_name = Map("key1" -    > "val1", "key2" -> "val2", … )

If use Map, you need to import scala. collection. mutable. Map

The operating methods of Map are as follows:

map_name. keys  // return a Map with all keys

map_name. values  // return a HashMap with all values

map_name    . isEmpty         // return true if the Map is empty

Example 7.5

import scala. collection. mutable. Map

object Map001 {

def main(args: Array[String]) {

val house = Map("door" -> "big",

"window" -> "small",

"wall" -> "high")

val house0 = Map()     // define an empty Map

println( "All keys in the map are : ")

println( house.keys )

println( "All values in the map are : " )

println( house.values )

println( "The hourse is empty ? " + house.isEmpty )

println( "The hourse0 is empty ? " + house0.isEmpty )

}}

Output:

All keys in the map are :

Set( window, door, wall )

All values in the map are :

HaspMap( small, big, high )

The house is empty ? false

The house0 is empty ? true

Explanation:

map_name. keys  // return a Set with all keys

map_name. values  // return a HashMap with all values

map_name. isEmpty         // return true if the Map is empty

Connect Two Maps

The syntax to connect two Maps is as follows:

map1 ++ map2

Example 7.6

object Map004 {

def main(args: Array[String]) {

val colors1 = Map("green" -> "#006600", "purple" -> "#ff00ff")

val colors2 = Map("grey" -> "#666666", "black" -> "#000000")

var colors = colors1 ++ colors2    // connect two maps

println( "The connected map is : "  )

println( colors )

}}

Output:

The connected map is:

Map( green -> 　#006600,  purple -> 　#ff00ff,  grey -> 　#666666,  black -> 　#000000 )

Explanation:     “colors1 ++ colors2” connects two maps

Map Key & Value

Using “foreach()” can get the Map keys and Values.

map_name    . keys. foreach ( k => map(k) )

For every loop iteration, each key of the map element is assigned to “k”, each value is assigned to “map(k)”, until iterates the last map element.

Example 7.7

object Map002 {

def main(args: Array[String]) {

val books = Map("title" -> "Rust in 8 Hours",

"author" -> "Ray Yao",

"website" -> "www. amazon. com")

books.keys.foreach { k =>        // iteration

print( "Key is: " + k )

println(".    Value is: " + books(k) )}

}

}

Output:

Key is title.   Value is Rust in 8 Hours

Key is author.   Value is Ray Yao

Key is website.   Value is www. amazon. com

Explanation:

“books. keys. foreach{ k => books(k)}” outputs each book’s title and each book’s value.

Hour 8

Class/Object

Tuple

Tuple is a kind of collection that can contain different types of elements.

The syntax to create a Tuple is as follows:

val tuple_name = ( Int_val,  Float_val,  String_val,… )

The syntax to access the elements of Tuple is as follows:

tuple_name. _1    // access the first element

tuple_name. _2    // access the second element

tuple_name    . _3    // access the third element

Example 8.1

object Test {

def main(args: Array[String]) {

val t = (100, 200.88, "Go in 8 Hours")     // create a tuple

println( t._1 )      // access the first element

println( t._2 )      // access the second element

println( t._3 )      // access the third element

}

}

Output:

100

200

Go in 8 Hours

Explanation:

“val t = (100, 200. 88, "Go in 8 Hours") “ creates a tuple

“println( t. _1 )” accesses the first element

“println( t. _2 )” accesses the second element

“println( t. _3 )” accesses the third element

Tuple Iteration

The syntax to iterate the Tuple elements is as follows:

tuple_name    . productIterator. foreach{ k => v }

“k” is the keys of the tuple.

“v” is the values of the tuple.

Example 8.2

object Tup001 {

def main(args: Array[String]) {

val t = (10, 20, 30, 40, 50)

t.productIterator.foreach {       // iterate the tuple

k => println("The value is : " + k )

}}}

Output:

The value is : 10

The value is : 20

The value is : 30

The value is : 40

The value is : 50

Explanation:

“t. productIterator. foreach{ k=>v} iterates all elements of the tuple.

Scala Iterator

Iterator is used to access all elements in a collection.

The syntax to use Iterator is as follows:

val obj = Iterator("val1", "val2", "val3", "val4")

“obj” is an object of Iterator.

The operating methods of Iterator are as follows:

obj. next()    // access the next element of the iterator

obj    . hasNext     // check if the next element exists

Example 8.3

object Test {

def main(args: Array[String]) {

val obj = Iterator("C#", "in", "8", "Hours")    // use iterator

while (obj.hasNext ){    // check if the next element exists

Print (obj. next () + " ")    // access the next element

}}}

Output:

C# in 8 Hours

Explanation:

“val obj = Iterator("C#", "in", "8", "Hours") “ uses an iterator.

“obj. hasNext)” checks if the next element exists

“obj. next()” accesses the next element in the iterator.

Useful Function in Iterator

There four useful functions in Iterator:

obj. max    // get the maximum value in the iterator

obj. min      // get the minimum value in the iterator

obj. size      // get the number of elements in the iterator

obj    . length   // get the number of elements in the iterator

“obj” is an iterator object

Example 8.4

object It003 {

def main(args: Array[String]) {

val obj1 = Iterator(10,20,30,40,50)

println("The minimum value is : " + obj1.min )

val obj2 = Iterator(60,70,80,90)

println("The maximum value is : " + obj2.max )

val obj3 = Iterator("C#", "in", "8", "Hours")

println("The number of elements is : " + obj3.size )

val obj4 = Iterator("C#", "Interview", "Exam")

println("The number of elements is : " + obj4.length )

}}

Output:

The minimum value is : 10

The maximum value is : 90

The number of elements is : 4

The number of elements is : 3

Explanation:

obj. max    // get the maximum value in the iterator

obj. min      // get the minimum value in the iterator

obj. size      // get the number of elements in the iterator

obj. length   // get the number of elements in the iterator

Class

Class is an abstract concept, a class represents the commonness and characteristics of something or someone.

Objects are concrete things or people, an object is an instance of one thing or person.

Class is an abstraction of an object, Object is a concrete instance of a class. For example: If the vehicle is a class, then your car is an object.

(1) The syntax to define a class is as follows:

class Class_Name ( parameters ){

……

}

The first letter of class name should be capitalized.

Example 8.5

class Color ( num: Int ){

……

}

Explanation:

“Color” is a class name

“num: Int” is a parameter.

Object

An object is an instance of a class.

val obj = new Class_Name(  );   // create an object

obj. variable_name

obj    . function_name( )

“obj = new Class_Name( );” creates a new object named “obj” for the class.

“obj. variable;” means that “obj” references a variable.

“obj. function_name ( );” means that “obj” references a method.

Example 8.6

val obj = new Color(  ) ;   // create an object “obj”

obj. c1= “yellow";   // an object references a variable c1

obj. c2=”purple”;     // an object references a variable c2

obj    . brightness ( );   // an object calls a method brightness()

Explanation:

“val obj = new Color;” creates an object named ”obj”, then references variable “c1” and “c2”.

“obj. brightness ( );” calls the function “brightness ( );”

Class & Object

Example 8.7

import java. io. _    // import the java package for class & object

class MyClass(val a: Int, val b: Int) {   // define a class

var x: Int = 0     // the member of the class

var y: Int = 0     // the member of the class

def func(){     // the member of the class

x = a * 2

y = b * 3

}

}

object Study {

def main(args: Array[String]) {

val obj = new MyClass(100, 200)    // create an object

obj.func()      // the object calls the method

println ( obj.x );     // the object references the variable x

println ( obj.y );     // the object references the variable y

}}

Output:

200

600

Explanation:

“class MyClass(val a: Int, val b: Int) {  }” defines a class.

“val obj = new MyClass(100, 200)” creates an object.

“obj. func()”: the object calls the method func()

“obj. x” : the object references the variable x

“obj. y” : the object references the variable y

Appendix 1

Extends

A class can be extended by a subclass. The subclass will inherit all members of the super class.

If the parameter or method in the subclass overrides the parameters or method in the super class, you should use the keyword “override”.

The syntax to extend a super class is as follows:

class SubClass (override arg    : type) extends SuperClass(arg)

Example A1

import java. io. _    // import the java package for class & object

class MyClass (val a: Int, val b: Int) {   // super class

var x: Int = 0     // the member of the class

var y: Int = 0     // the member of the class

def func(){     // the member of the class

x = a * 2

y = b * 3

}

}

class SubClass(override val a: Int, override val b: Int) extends MyClass (a, b){      // subclass extends the super class

var z: Int = a + b      // the member of the subclass

}

object Study {

def main(args: Array[String]) {

val obj = new SubClass (100, 200)  // create a sub object

obj. func()     // func() becomes a member of the subclass

println ( obj. x);   // x becomes a member of the subclass

println ( obj. y);   // y becomes a member of the subclass

println ( obj. z);

}

}

Output:

200

600

300

Explanation:

class SubClass(override val a: Int, override val b: Int) extends MyClass (a, b){   }   // subclass extends the super class

While a subclass extends a super class, the subclass will inherit all members of the super class.

Access Modifiers

The access modifiers of Scala are: private, protected, and the public. “public” is a default access modifier.

Private

The private members in the nested class cannot be accessed by the outer class.

The private members in the current class cannot be accessed by the other class.

The private member in the current class can be only accessed by the current class.

Example A2

object Acc000{

class Study{

private def func(){ println("……") }   // private function

......

func()   // Correct ! Call a private function in the same class

}

class Another{

obj.func()   // Error! Call a private function in another class

}

}

Explanation:

“private def func(){ println("…") }“ defines a private function

“func()”: Correct! Call a private function in the same class.

“obj. func()”:   Error! Call a private function in another class.

Example A3

import java. io. _

class MyClass(val a: Int, val b: Int) {

var x: Int = 0

var y: Int = 0

private def func(){     // define a private method

x = a * 2

y = b * 3

}

func()   // Correct ! Call the private method in the same class

}

object Study {

def main(args: Array[String]) {

val obj = new MyClass(100, 200)

println ( obj. x );

println ( obj. y );

}

}

Output:

200

600

Explanation:

“private def func(){   }” defines a private method.

“func()”  calls the private method in the same class successfully! Correct!

Protected

A Protected member can be accessed by a subclass of the class, and cannot be accessed by another class.

Example A4

class Super{

protected def m() {     // define a protected member

println("...... ")

}

}

class Sub extends Super{      // inherit

m()     // Correct ! Subclass can access the protected member

}

class Another{

obj.m() // Error!  Another class can ’ t access protected member

}

Explanation:

“protected def m() { }”defines a protected member.

“m()”: Correct! Subclass can access the protected member

“obj. m()”: Error! Another class can’t access protected member

Example A5

import java. io. _

class MyClass(val a: Int, val b: Int) {

var x: Int = 0

var y: Int = 0

protected def func(){     // define a protected member

x = a * 2

y = b * 3

}

}

class SubClass(override val a: Int, override val b: Int) extends MyClass (a, b){     // inherit

var z: Int = a + b

func()   // OK ! SubClass can accesses the protected member .

}

object Study {

def main(args: Array[String]) {

val obj = new SubClass(100, 200)

println ( obj. x );

println ( obj. y );

println ( obj. z );

}

}

Output:

200

600

300

Explanation:

“protected def func(){  }” defines a protected member.

“func()”:   SubClass can accesses the protected member successfully. Correct!

Exception

If an exception happens in Scala program,  Scala terminates the code by throwing an exception

The Scala program usually has following exceptions:

Column 1

Column 2

ArithmeticException

ArrayStoreException

AwtException

ClassCastException

ClassNotFoundException

IllegalArgumentException

IndexOutOfBoundsException

InstantiationException

InterruptedException

NoSuchMethodException

NumberFormatException

RuntimeException

EOFException

FileNotFoundException

InterruptedIOException

IOException

UTFDataException

To resolve the exceptions in column 1, please import Java. lang. *

To resolve the exceptions in column 2, please import Java. io. *

The syntax to handle the exception is as follows:

try {     // try some code where exception may happen

} catch {    // catch one of the exceptions

case e: Exception 1 => {

}

case e: Exception 2 => {

}

case e: Exception 3 => {

}

} finally {      // must execute

}

Example A6

import java. io. FileReader

import java. io. FileNotFoundException

import java. lang. RuntimeException

import java. lang. NumberFormatException

object Except000 {

def main(args: Array[String]) {

try {  // try some code where the exception may happen

val myFile = new FileReader("myFile. txt")

} catch {    // catch one of the exceptions

case e: FileNotFoundException => {

println("The file cannot be found. ")

}

case e: RuntimeException => {

println("Runtime Exception")

}

case e: NumberFormatException => {

println("Number Format Exception")

}

} Finally {     // must execute

println("Check the file carefully! ")

}

}

}

Output:

The file cannot be found.

Check the file carefully!

Explanation:

Assume myfile. txt does not exist, so exception happens.

“try {  }” tries some code where exception may happen

“catch {  }” catches one of the exceptions.

“Finally {  }”  must execute these codes.

Appendix 2

Tests

Please choose the correct answer.

01.

fill in HelloWorld {      // This is a Hello World program

def main(args: Array[String]) {

println("Hello, world! ")

}

}

A. program     B. class     C. public     D. object

02.

object Var001 {

def main(args: Array[String]){

var myVar1: fill in = 1000    // declare a data type

print(myVar1)

}

}

A. string     B. float     C. Int     D. int

03

object Ifelse001 {

def main(args: Array[String]) {

var a=100; var b=200;

if (a>b) {print ("a is greater than b. ")}

fill in { print ( "a is less than b" );}     // do this

}

}

A. then     B. else     C. than     D. otherwise

04.

object Test {

def main(args: Array[String]) {

println( "The result is : " + mul(50,2) );   // call the method

}

fill in mul( x: Int, y: Int ) : Int = {   // define a method

var result: Int = 0

result = x * y

return result        // return value

}

}

A. function     B. void     C. method     D. def

05.

object Arr000 {

def main(args: Array[String]) {

var color = fill in ("Red", "Blue", "Green")    // create an array

print( color(0) )    // access the first array element

}

}

A. Array     B. new Array     C. array     D. new array

06.

list_name. head   // returns the first element of the list

list_name. tail   // returns fill in ?

list_name. isEmpty   // returns true when the list is empty

1. the last element of the list

2. an empty list

3. a list except the first element

4. an zero element in the end.

07.

// create a tuple

val t = fill in 100, 200. 88, "Go in 8 Hours" fill in

A. [     ]       B. (     )        C. {     }        D. <     >

08.

The syntax to extend a super class is as follows:

class SubClass (override arg    : type) fill in SuperClass(arg)

A. inherit        B. inherits        C. extend        D. extends

09.

About Multi-line String Type

Multi-line String Type are defined by fill in quotes.

A. single        B. double        C. treble        D. quadruple

10.

object Val002 {

def main(args: Array[String]){

fill in Con1 = "C# in "     // define a constant

fill in Con2 : Int = 8        // define a constant

fill in Con3 : String = " Hours"     // define a constant

print(Con1 + Con2 + Con3);

}

}

A. val        B. var        C. const        D. constant

11.

object For001 {

def main(args: Array[String]) {

var y = 0;

for( y <- 0 fill in 8){   // run 7 times

print( y );

}

}

}

A. to        B. till      C. <      D. until

12.

About Closure: the left part of the arrow is _______, the right part of the arrow is the function body.

var variable = (     fill in ) => function body

A. a closure name

B. a parameter list

C. a return type

D. a loop statement

13.

The syntax to create an array is as follows:

val array_name = fill in [Type](length)

array-name(index0) = value0;

array-name(index1) = value1;

array-name(index2) = value2;

A. Array     B. new Array     C. array     D. new array

14.

object conlist000 {

def main(args: Array[String]) {

val title1 = List("Java", "in")

val title2 = List("Ruby", "in")

val title3 = List("8", "Hours")

println(title1 fill in title3)     // connect two lists

println(List. concat(title2, title3))   // connect two lists

}

}

A. :         B. ::         C. :::         D. ::::

15.

The syntax to define a class is as follows:

fill in ( parameters ){

……

}

A. Class_Name Class

B. Class_Name class

C. Class Class_name

D. class Class_Name

16.

Which following statement is not correct?

A. The private members in the nested class cannot be accessed by the outer class.

B. The private members in the current class cannot be accessed by the other class.

C. The private member in the current class can be only accessed by the current class.

D.   The private members in the nested class can be accessed by the outer class.

17.

Which following statement is not correct?

A. The first letter of all class names should be capitalized.

B. All method names start with a lowercase letter.

C. Scala is a case-insensitive language.

D. A semicolon is used to end a line of statement.

18.

What is the output according to the following code?

object log000 {

def main(args: Array[String]) {

var x=true; var y=false;

var a = x && y;   print ( a + “ “ );

var b = x || y;   print ( b + “ “  );

var c = ! x;   print ( c + “ “  );

}

}

A. true  false  false

B. false  true  false

C. true  true  false

D. false  false true

19.

object For000 {

def main(args: Array[String]) {

var x = 0;

for( x <- 0  fill in 8){    // run 8 times

print( x );

}

}

}

A. to        B. till      C. <      D. until

20.

object Con000 {

def main(args: Array[String]) {

var str1 = "JAVA";

var str2 =  "C#";

var str3 =  "in 8 Hours: ";

println( str1. fill in (str3) );    // connect two strings

println( str2 + str3 );

}

}

A. connect        B. join        C. concat        D. link

21.

import Array. _

object Rev000 {

def main(args: Array[String]) {

var myArray = Array(0, 1, 2, 3, 4)

for (a: Int <- myArray. fill in ){     // reverse elements

print(a + "  ")

}

}

}

A. reverse

B. reverse()

C. reverse. ArrayBuffer

D. reverse. toBuffer

22.

object Map004 {

def main(args: Array[String]) {

val colors1 = Map("green" -> "#006600", "purple" -> "#ff00ff")

val colors2 = Map("grey" -> "#666666", "black" -> "#000000")

var colors = colors1 fill in colors2   // connect two maps

println( "The connected map is : "  )

println( colors )

}

}

A. +        B. ++        C. +++        D. ++++

23.

val obj = fill in Class_Name(  );   // create an object

obj. variable_name( )

obj. function_name( )

A. create        B. object        C. new        D. class

24.

try {

} catch {

case e: Exception 1 => {

}

case e: Exception 2 => {

}

case e: Exception 3 => {

}

} fill in {      // must execute

}

A. last        B. lastly        C. final        D. finally

Answers

01 . D

13 . B

02 . C

14 . C

03 . B

15 . D

04 . D

16 . D

05 . A

17 . C

06 . C

18 . B

07 . B

19 . A

08 . D

20 . C

09 . C

21 . D

10 . A

22 . B

11 . D

23 . C

12 . B

24 . D

Scala Source Code Download Link:

https : //forms . aweber . com/form/76/1081568876 . htm

Source Code Download

Scala Source Code Download Link:

https : //forms . aweber . com/form/76/1081568876 . htm

Swift

Hour 1

Introduction

What is Swift?

Swift, a new development language released by Apple at WWDC Apple Developer Conference in 2014, runs alongside Objective-C on macOS and iOS platforms for building applications based on the Apple system.

Swift is a new programming language for writing iOS and macOS applications. Swift combines the advantages of C and Objective-C and is not limited by C compatibility. Swift uses a secure programming mode and adds a lot of new features that will make programming easier, more flexible, and more fun. Swift grew as the Cocoa and Cocoa Touch frameworks came of age. Swift shows the new direction of software development.

Swift, Apple claims, is fast, modern, secure, interactive and generally superior to Objective-C. The Xcode Playgrounds feature is the biggest innovation Swift has brought to Apple's development tools. It provides a powerful, interactive effect that enables Swift source code to display its running results in real time during the program writing process.

Swift Working Platform

Swift Online IDE

This book uses Online IDE as a Swift working Platform. Please click the following link, open the Swift Online IDE.

https : //www . tutorialspoint . com/compile_swift_online . php

If you want to run the Swift program, just copy and paste the Swift code in the “main.swift ” of Online IDE, and click the “Execute ” tag to run the program, then the result will be shown on the right-side window.

Note: “STDIN ” is used to input interactive data from a user.

If you don’t want to use Swift Online IDE, then please install Swift to your local computer.

Install Swift

Download Swift Xcode

If you don’t want to use Swift Online IDE, then please install Swift Xcode to your local computer.

You need to have a MAC, because the integrated development environment(XCode) only runs on OS X. The Operating System of your computer must be OS 10. 9. 3 or above.

The download links of Swift XCode as follows:

https : //developer . apple . com/xcode/download/

https : //swift . org/download/#latest-development-snapshots

Install Swift Xcode

When the download is complete, double-click the downloaded DMG file to install it.

Once the installation is complete, we need to move the Xcode icon into the Application folder.

Start Playground

“Playground” is used to run the Swift program.

So let's open up Xcode in the Application folder……

1.

After opening the Xcode, select “Get started with a playground”.

Or at the top of the Xcode screen, click the tags:

File -> New -> Playground

2.

In the Playground screen, please set up a name for Playground, for example: “MyPlayground”.

3.

Set up a platform as “iOS”.

4.

Click “Next ” button to start the Playground…...

5.

You can see the default code in the Playground as follows:

import UIKit

var str = "Hello, playground"

6.

The output in the right-side window:

Hello, playground

Congratulation! Your Swift IDE has been set up successfully!

The First Swift Program

The working platform of this book is Swift Online IDE, because some readers use Windows OS, some readers use Apple OS.

Example 1.1

var myString = "Hello, World! "

print(myString)

Output:

Hello, World!

Explanation:

“var” is used to declare a variable.

“myString” is a variable.

“Hello, World! ” is a string.

“print()” is an  output command, which shows the value of the variable.

Swift Comment

//    is used in a single - line comment

/*…… */    is used in multi-line comments

The comment symbol is always ignored by the Swift parser.

Example 1.2

var myString = "Hello, World! "   // var declares a variable

print(myString)      /* “myString” is a variable.

“print()” is an  output command, which shows the value of the variable.  */

Output:

Hello, World!

Explanation:

//    is used in a single - line comment

/*…… */    is used in multi-line comments

The comment is always not executed.

Semicolon

;

Swift does not use semicolon as an ending symbol of each line, but when you write multiple statements on the same line, you must separate them with semicolons.

Example 1.3

// semicolon example

var str = "Hello    ! " ; print(str)

Output:

Hello!

Explanation:

“var str = "Hello! " ; print(str)”: There are two different statements on the same line, which need a semicolon to separate them.

Identifier

Identifiers are the names given to variables, constants, methods, functions, enumerations, structures, classes, and so on.

The rules of the Swift identifier are:

* Case Sensitive

* Identifiers can start with an underscore ( _ ) or a letter

* Identifiers can not start with a number

* If you want to use a keyword as an identifier, you can add an accent ( ` ) before and after the keyword

Example 1.4

JQuery and jQuery is two different identifiers.

3Cars is an invalid identifier.

Cars3 is a valid e identifier.

` public ` is a valid identifier.

Note:

` is an accent, it is not a single quote.

` key locates in the same key with ~ key on keyboard.

Swift Keywords

Keywords are reserved and used by Swift language itself. Any variable name, constant name, function name, array name… cannot use keyword as their name.

The following chart lists basic Swift keywords:

class

deinit

enum

extension

func

import

init

internal

let

operator

private

protocol

public

static

struct

subscript

typealias

var

where

while

break

case

continue

default

do

else

fallthrough

for

if

in

return

switch

as

dynamicType

false

is

nil

self

Self

super

associativity

convenience

dynamic

didSet

final

get

infix

inout

lazy

left

mutating

none

nonmutating

optional

override

postfix

precedence

prefix

Protocol

required

right

set

Type

unowned

weak

willSet

true

false

_COLUMN_

_FILE_

_FUNCTION_

_LINE_

Swift Space

There should be a space between an operator and any variable, constant, number    .

Example 1.5

var x= 10 + 20     // error

var x = 10 + 20    // correct

let y = 30+ 40     // error

let y =     30 + 40    // correct

Explanation:

In “x=”,  there is no a space between x and =, it is incorrect.

In “30+”, there is no a space between 30 and +, it is incorrect.

"var" is used to declare a variable.

"let" is used to declare a constant.

User Input

“readLine()” is used to accept the input from a user.

let variable = readLine()

In Online IDE, “STDIN” is used to input data from a user.

Example 1.6

print("Please enter your name: ")

if let name = readLine() {

print(name)

}         // Assume that I input my name “Ray Yao”

Output:

Please enter your name:

Ray Yao

Explanation:

“let name = readLine ()” accepts the data input from a user, and assigns the value to the constant “name”.

Hour 2

Basics

Data Type

All variables have data types. When declaring a variable, you must specify its data type.

There are several main data types in Swift as follows:

Type

Description

Bool

Bool has three values: true, false, nil.

e    . g.    true

String

Characters enclosed by double quotes.

e    . g.  “Scala in 8 Hours”

Character

A single letter enclosed by double quotes.

e    . g.   “c”

Optional

Deal with a situation of missing value.

e    . g. A variable with a value or without value.

The next chart will list the data type about number variables.

Type

Size

Range

Int8

1 byte

-128 ~ 127

Signed type integer

UInt8

1 byte

0 ~ 255

Unsigned type integer

Int32

4 bytes

-2147483648 ~ 2147483647

Signed type integer

UInt32

4 bytes

0 ~ 4294967295

Unsigned type integer

Int64

8 bytes

-9223372036854775808 ~ 9223372036854775807 integers

UInt64

8 bytes

0 ~ 18446744073709551615

Unsigned type integer

Float

4 bytes

1. 2E-38 ~ 3. 4E+38

(~6 digits)

Double

8 bytes

2. 3E-308 ~ 1. 7E+308

(~15 digits)

Alias of Data Type

We can give an alias to a data type by using “typealias”.

typealias alias = type

Example 2.1

typealias miles = Int

var highway: miles = 200

print(highway)

Output:

200

Explanation:

“typealias miles = Int” defines an alias “miles” for the data type “Int”.

Then, “miles” is a data type “Int”.

Code Checks

Swift does code checking automatically when compiling your code, to make sure that the code is safe.

Example 2.2

var myVariable = "C# in 8 Hours"

myVariable = 100

print(myVariable)

Output:      (error message)

mai n . swif t : 2 : 1 4 : erro r : cannot assign value of type 'Int' to type 'String'

myVariable = 100

^~~

Explanation:

“var myVariable = "C# in 8 Hours"” defines the data type of “myVariable” as a String.

“myVariable = 100” wants to define a data type of “myVariable” as an Int again, so an error occurs.

Type Inference

If you do not explicitly specify a type for a variable, Swift will use “Type Inference” feature to select the appropriate type.

Example 2.3

var myVariable = 100

// “myVariable” will be inferred as an Int type by Swift .

// “var” is used to declare a variable .

Example 2.4

let e = 2. 7182818

// “e” will be inferred as a Double type by Swift .

// “let” is used to declare a constant .

Example 2.5

var myBook = "Shell Scripting in 8 Hours"

// “myBook” will be inferred as a String type by Swift .

Variable Declaration

“var” can be used to declare a variable.

The value of the variable is changeable at runtime.

var name    : type = value

“type” is optional to declare a data type.

Example 2.6

var myVar = 100

print(myVar)

var e:Double = 2. 7182818      // double type

print(e)

Output:

100

2. 7182818

Explanation:

“var myVar” declares a variable “myVar”.

“var e: Double” declares a variable “e”.

Variable Name

Variable names can be letters, numbers, underscores.

Variable names cannot start with a number.

Variable names are case sensitive    .

Example 2.7

var _var = 800

print( _var )

var mp3 = "Good Musics! "

print(mp3)

Output:

800

Good Musics!

Explanation:

“_var” is a valid variable name.

“mp3” is a valid variable name.

Output Variable Value

If want to output a variable value that is inside the double quotes, you can use backslashes and parentheses to insert variables.

“ \(variable) ”

Example 2.8

var title = "'R in 8 Hours'"

var author = "Ray Yao"

print("The author of     \(title) is \(author) ")

Output:

The author of 'R in 8 Hours' is Ray Yao

Explanation:

“ \(variable) ” can output the variable value that is inside the double quotes.

Constant Declaration

“let” can be used to declare a constant.

The value of the constant is unchangeable at runtime.

let name    : type = value

“type” is optional to declare a data type.

Example 2.9

let myCon = 100

print(myCon)

let e:Double = 2. 7182818      // double type

print(e)

Output:

100

2. 7182818

Explanation:

“let myCon” declares a Constant “myCon”.

“let e: Double” declares a Constant “e”.

Constant Name

Constant names can be letters, numbers, underscores.

Constant names cannot start with a number.

Constant names are case sensitive    .

Example 2.10

let _con = 800

print( _con )

let mp4 = "Good Movies! "

print(mp4)

Output:

800

Good Movies!

Explanation:

“_con” is a valid constant name.

“mp4” is a valid constant name.

Output Constant Value

If want to output a constant value that is inside the double quotes, you can use backslashes and parentheses to insert constants.

“ \(constant) ”

Example 2.11

let title = "'Kotlin in 8 Hours'"

let author = "Ray Yao"

print("The author of     \(title) is \(author) ")

Output:

The author of 'Kotlin in 8 Hours' is Ray Yao

Explanation:

“ \(constant) ” can output the constant value that is inside the double quotes.

Print Attributes

Print statement has “separator” and “terminator” attributes.

print("… ", separator    : " " , terminator: " ")

Example 2.12

print ("Scala", "in", "8", "Hours",

separator: "**" , terminator: "! ")

Output:

Scala**in**8**Hours!

Explanation:

In above print statement,

the separator is “**”,

the terminator is “! ”.

Hour 3

Operators

Optional Type

An optional type variable means that it may have no value, may have a value. Using a “? ” can define an optional type variable.

var myVariable    : Type?

If myVariable has a value, the “! ” can get the value.

myVariable     !

//  ! can get the value of optional variable

Example 3.1

var myVar:String?

myVar = "Rust in 8 Hours"

print(     myVar! )

Output:

Rust in 8 Hours

Explanation:

“myVar: String? ” defines myVar as an optional type by using “? ”

“myVar! ” gets the value of myVar by using “! ”

Nil Value

1.

If an optional variable has no initial value, its default value is “nil”    .

Example 3.2

var myVar:String?        // myVar has no initial value

if myVar == nil {            //  ‘==’ checks if they are equal

print("The value of myVar is nil")

}

Output:    The value of myVar is nil

2.

Using the “    ! ” to get a nil value will cause a runtime error.

Example 3.3

var myVar: String?

if myVar == nil {

print(myVar! )        // use ! to get myVar’s value

}

Output:    Fatal Error……

“ ! ” Declaration

“! ” can declare an optional variable too, in this case, you don’t need to use “! ” to get the value of an optional variable.

var myVariable    : Type !

Example 3.4

var myVar:String!       // use ! to declare myVar

myVar = "Django in 8 Hours"

print( myVar )             // don’t need ! to get the value

Output:

Django in 8 Hours

Explanation:

“var myVar: String! ” uses “! ” to declare an optional variable.

“print( myVar )” does not use “! ” to get the value.

Arithmetical Operators

Operators

Running

+

add or connect strings

-

subtract

*

multiply

/

divide

%

get modulus

% modulus operator divides the first operand by the second operand, returns the remainder. e. g. 4%2, the remainder is 0.

Example 3.5

var add = 100 + 200;   print (add)    // output 300

var div = 800 / 2;   print ( div )          // output 400

var mod = 10     % 3;   print ( mod )     // output 1

Explanation:

var add=100+200;   print ( add ) will output  300

var div=800/2;   print ( div ) will output  400;

var mod=10%3;   print ( mod ) will output  1;

Logical Operators

Operators

Equivalent

Return

&&

and

true or false

||

or

true or false

!

not

true or false

Example 3.6

var x = true; var y = false

var a = x && y;   print ( a )   // output : false

var b = x || y;   print ( b )   // output : true

var c =     ! x;   print ( c )   // output :   false

Explanation:

true && true;

returns true;

true && false;

returns false;

false &&false;

returns false;

true II true;

returns true;

true II false;

returns true;

false II false;

return false;

! false;

returns true;

! true;

returns false;

Assignment Operators

Operators

Examples:

Equivalent:

+=

x+=y

x=x+y

-=

x-=y

x=x-y

*=

x*=y

x=x*y

/=

x/=y

x=x/y

%=

x%=y

x=x%y

Example 3.7

var x = 200;   var y = 100

x %= y;  print ( x )   // output  0

x += y;   print ( x )   // output  100

x     /= y;    print ( x )   // output  1

Explanation:

x % y;    // x = x % y;

x += y;   // x = x + y;

x / = y;   // x = x / y;

Comparison Operators

Operators

Running

Return

>

greater than

true or false

<

less than

true or false

>=

greater than or equal

true or false

<=

less than or equal

true or false

==

equal

true or false

! =

not equal

true or false

Example 3.8

var a = 100; var b = 200

print(a == b)    // false

print(a != b)     // true

print(a > b )     // false

print(a < b)      // true

print(a >= b)    // false

print(a     <= b)    // true

Conditional Operator

(test-expression)     ? (if-true-do-this) : (if-false-do-this);

( test-expression) looks like a<b, x! =y, m==n. etc.

Example 3.9

var a = 100; var b = 200

var result = ( a < b ) ? "apple" : "banana"

// (test-expression) ? (if-true-do-this) : (if-false-do-this);

print ( result )

Output:

apple

Explanation:

The conditional operator use (a<b) to test the “a” and “b”, because “a” is less than “b”, it is true. Therefore, the output is “apple”.

Range Operator

The range operator defines a number range from one value to another value.

There are two kinds of range operators in Swift:

1.

value1    … value2

For example:

“1…6 ” means that its range value is 1, 2, 3, 4, 5, 6.

2.

value1    .. < value2

For example:

“1.. <6 ” means that its range value is 1, 2, 3, 4, 5.

Precedence of Operators

Operators

Precedence

Logincal Not

!

Mul   Div   Mod

*  /    %

Add   Sub

+  -

Range

...    .. <

Compare

! =   >=  <=   >   <   ==

Logical And

&&

Logical Or

||

Conditional

?   :

Assignment

%=  /=  *=  +=      - =   =

Character

A character usually means a single letter enclosed by a double quote. For example: “C”.

Example 3.10

var cha1: Character = "X "

var cha2: Character = "Y "

print("The value of cha1 is \(cha1)")

print("The value of cha2 is \(cha2)")

Output:

The value of cha1 is X

The value of cha2 is Y

Explanation:

var cha1: Character = "X " defines a character X as cha1.

var cha2: Character = "Y " defines a character Y as cha2.

Append Character

“append()” can append a character to a string.

string    . append(character)

Example 3.11

var string1: String = "computer language: "

var letter2: Character = "R"

string1.append ( letter2 )

print("Learn a \(string1)")

Output:

Learn a computer language: R

Explanation:

“string1. append( letter2 )” appends a leter2 to string1.

Hour 4

Statements

Escape Sequences

The “ \ ” backslash character can be used to escape characters.

\b makes a backspace

\n outputs content to the next new line.

\r makes a return

\t makes a tab

\’ outputs a single quotation mark.

\” outputs a double quotation mark.

Example 4.1

print("He said \" Hello \n World! \" ")

//  \” outputs a double quote

// \n outputs contents to a new line .

Output:

He said "Hello

World! "

Explanation:

\” outputs a double quotation mark.

\n outputs the contents into a new line.

If Statement

if ( test-expression ) {       // if true do this   }

“if statement” executes codes inside { … } only if a specified condition is true, does not execute any codes inside {…} if the condition is false.

Example 4.2

var a = 200; var b = 100

if a > b {   // if true, do this

print ( "a is greater than b" )

}

Output:

a is greater than b

Explanation:

( a>b ) is a test expression, namely (200>100), if returns true, it will execute the codes inside the { }, if returns false, it will not execute the codes  inside the { }.

If-else Statement

if ( test-expression) {   // if true do this    }

else  {      // if false do this    }

“if... else statement” runs some code if a condition is true and runs another code if the condition is false

Example 4.3

var a = 100; var b = 200

if a > b  {  // if true do this

print ("a is greater than b. ")

}

else {  // if false do this

print ( "a is less than b" )

}

Output:

a is less than b

Explanation:

( a>b ) is a test expression, namely (100>200), if returns true, it will output  ”a is greater than b. ” if returns false, it will output “a is less than b”.

Switch Statement

switch ( variable ) {

case 1: if equals this case, do this

case 2: if equals this case, do this

case 3: if equals this case, do this

default : if not equals any case, run default code

}

The value of the variable will compare each case first, if equals one of the “case” value; it will execute that “case” code.

Example 4.4

var number = 20

switch ( number ) {   // number value compares each case

case 10 : print ( "Running case 10" )

case 20 : print ( "Running case 20" )

case 30 : print ( "Running case 30" )

default : print ( "Running default code" )

}

Output:    Running case 20

Explanation:     The number value is 20; it will match case 20, so it will run the code in case 20.

Fallthrough Statement

“fallthrough” works between “case 1…case n” statements.

switch ( variable ) {

case 1: if equals this case, do this

……

fallthrough

case n: must do the next one.

……

default : if not equals any case, run default code

}

“fallthrough” is used to continue to execute the next case statement, regardless of whether the condition is met or not.

Example 4.5

var number = 20

switch ( number ) {   // number value compares each case

case 10 : print ( "Running case 10" )

case 20 : print ( "Running case 20" )

fallthrough

case 30 : print ( "Running case 30" )      // run this too

case 40 : print ( "Running case 30" )

default : print ( "Running default code" )

}

Output:

Running case 20

Running case 30

Explanation:

After using “fallthrough” statement, although the “case 30” does not meet the condition, it still executes.

For-in Loop

“For-in loop” is used to iterate over all the elements in a collection.

for index in collection {     ...... }

“index” means the index of each element in the collection.

Example 4.6

for key in 1... 4 {

print("\(key) adds 2 equal to: \(key + 2)")

}

Output:

1 adds 2 equal to: 3

2 adds 2 equal to: 4

3 adds 2 equal to: 5

4 adds 2 equal to: 6

Explanation:

“for key in 1... 4” iterates over all elements in range 1… 4.

While Loop

while ( test-expression ) { …… }

“while loop” loops through a block of code if the specified condition is true.

Example 4.7

var key = 1

while key < 4 {

print( "The value of the key is \(key)")

key = key + 1

}

Output:

The value of the key is 1

The value of the key is 2

The value of the key is 3

Explanation:

“key< 4” is a test expression, if the condition is true, the code will loop less than 4 times, until the key is 4, then the condition is false, the code will stop running.

Repeat-While Loop

repeat{ …… } while ( test-expression);

“repeat... while” loops through a block of code once, and then repeats the loop if the specified condition is true.

Example 4.8

var key = 1

repeat {

print( "The value of the key is \(key)")

key = key + 1

}    while key < 4

Output:

The value of the key is 1

The value of the key is 2

The value of the key is 3

Explanation:

“key<4” is a test expression, if the condition is true, the code will loop less than 4 times, until the counter is 4, then the condition is false, the code will stop running.

Continue Statement

“continue” command works inside the loop.

continue

“continue” keyword is used to skip the current iteration, ignoring the following code, and then continue the next loop.

Example 4.9

var num=0

while  num < 10 {

num = num + 1

if num == 5 {

continue     // go the next while loop

}

print( num )

}

Output:

1

2

3

4

6

7

8

9

10

Explanation:

Note that the output has no 5.

“if num==5  continue;” means: When the num is 5, the program will run “continue” command, skipping the next command “print( num )”, and then continue the next while loop.

Break Statement

break

“break” keyword is used to stop the running of a loop according to the condition.

Example 4.10

var num = 0

while num < 10 {

if num == 5 {

break    // leave the while loop

}

num = num + 1

}

print( num )

Output:       5

Explanation:

“if num==5  break;” is a break statement. If num is 5, the program will run the “break” command, the break statement will leave the loop, then run “print(num)”.

Hour 5

String/Array

String

A string is a collection of many characters, the string is always enclosed by a pair of double quotes.

“ string ”

Example 5.1

var str1 = "Shell Scripting in 8 Hours "

print( str1 )

let str2 = "C# in 8 Hours "

print( str2 )

Output:

Shell Scripting in 8 Hours

C# in 8 Hours

Explanation:

“Shell Scripting in 8 Hours” is a string.

“C# in 8 Hours” is a string.

String Connection

Strings can be connected by using “+” operator.

string1 + string2

Example 5.2

let str1 = "Kotlin"

let str2 = " in 8 Hours"

var myStr = str1 + str2       // connection

print( myStr )

Output:

Kotlin in 8 Hours

Explanation:

“str1 + str2” connects two strings.

String Length

“string. count” can get the size of a string.

string    . count

Example 5.3

var str = "POWERSHELL"

print( "The length of \(str) is: " )

print( "\(    str.count )" )

Output:

The length of POWERSHELL is:

10

Explanation:

“str. count” returns the size of the string “str”.

String Comparison

“==” is used to compare two strings to check if they are equal.

string1 == string2

Example 5.4

var str1 = "'C# in 8 Hours'"

var str2 = "'Go in 8 Hours'"

if str1 == str2 {

print( "\(str1) is equal to \(str2) " )

} else {

print( "\(str1) is not equal to \(str2) " )

}

Output:

'C# in 8 Hours' is not equal to 'Go in 8 Hours'

Explanation:

“str1 == str2” compares two strings to check if they are equal.

String Empty Value

“isEmpty” can check if the value of a string is empty.

string    . isEmpty

Example 5.5

var myString = ""

if myString.isEmpty {

print( "myString is empty" )

} else {

print( "myString is not empty" )

}

Output:

myString is empty

Explanation:

“myString. isEmpty” checks if the value of the string is empty.

Creating Array (1)

An array is a particular variable, which can contain one or more value at a time.

The syntax to create an array:

var myArray = [Int]()        // create an array

myArray. append(value1)

myArray. append(value2)

myArray    . append(value3)

“myArray. append(value)” assigns a value to the array.

Example 5.6

var myArray = [Int]()

myArray.append (100)

myArray.append (101)

myArray.append (102)

print( "#0 element value is \(myArray[0])" )

print( "#1 element value is \(myArray[1])" )

print( "#2 element value is \(myArray[2])" )

Output:

#0 element value is 100

#1 element value is 101

#2 element value is 102

Explanation:

“var myArray = [Int]()” creates an Int type array “myArray”.

“myArray. append(100)” assigns value 100 to myArray.

“myArray. append(200)” assigns value 200 to myArray.

“myArray. append(300)” assigns value 300 to myArray.

There are three elements in myArray:

myArray[0] : its index is 0, its value is 100.

myArray[1] : its index is 1, its value is 101.

myArray[2] : its index is 2, its value is 102.

“index” also is called as “key” in Array.

Note that index begins from zero by default.

Creating Array (2)

The syntax to create an array with values is:

var myArray    : [type] = [val1, val2, val3, …]

“val1, val2, val3” are three elements of the myArray.

Example 5.7

var myArray:[Int] = [100, 101, 102]

print( "#0 element value is \(myArray[0])" )

print( "#1 element value is \(myArray[1])" )

print( "#2 element value is \(myArray[2])" )

Output:

#0 element value is 100

#1 element value is 101

#2 element value is 102

Explanation:

“var myArray: [Int] = [100, 101, 102]” creates an array with three element values.

Modifying Array

The syntax to modify an array is:

myArray[index] = value

Example 5.8

var myArray: [Int] = [100, 101, 102]

print( "#0 element value is \(myArray[0])" )

print( "#1 element value is \(myArray[1])" )

print( "#2 element value is \(myArray[2])" )

myArray[1] = 888

print( "#1 element value is \(myArray[1])" )

Output:

#0 element value is 100

#1 element value is 101

#2 element value is 102

#1 element value is 888

Explanation:

“myArray[1] = 888” modifies the value of the myArray[1] as 888.

Iterate Through Array

The syntax to iterate through all elements in an array is:

for element in myArray {……}

Example 5.9

var books = [String]()

books. append("R in 8 Hours")

books. append("C# in 8 Hours")

books. append("Go in 8 Hours")

for title in books {

print(title)

}

Output:

R in 8 Hours

C# in 8 Hours

Go in 8 Hours

Explanation:

“for title in books{……}” iterates through all elements “title” in the array “books”.

Merge Arrays

The syntax to merge two arrays is as follows:

array1 + array2

Example 5.10

var array1: [Int] = [100, 101, 102]

var array2: [Int] = [900, 901]

var array3 = array1 + array2

for element in array3 {

print(element)

}

Output:

100

101

102

900

901

Explanation:

“array1 + array2” merges two arrays as “array3”.

How Many Elements

The syntax to know how many elements is an array is:

array. count       // returns the length of the array

array    . isEmpty      // checks if the array is empty

Example 5.11

var array1: [Int] = [100, 101, 102]

var array2: [Int] = []

print("The size of array1 is \(array1.count )")

print("Is array2 empty?  \(    array2.isEmpty )")

Output:

The size of array1 is 3

Is array2 empty? true

Explanation:

“array1. count” returns the size of array1.

“array2. isEmpty” checks if the array2 is empty.

Hour 6

Collection

Dictionary

A dictionary is a data structure for storing pairs of values with the format  [key:value]. The dictionary’s keys should be unique. The type of each dictionary value should be the identical.

var dictionary: [keyType: valueType]

= [key1 : value1, key2: value2, key3: value3, …]

“dictionary[key]! ” can return a value of the dictionary.

Example 6.1

var myDict:[Int:String] = [1:"A", 2:"B", 3:"C"]

print( "key = 1, value is \(myDict[1]! )" )

print( "key = 2, value is \(myDict[2]! )" )

print( "key = 3, value is \(myDict[3]    ! )" )

Output:

key = 1, value is A

key = 2, value is B

key = 3, value is C

Explanation:

[1: "A", 2: "B", 3: "C"] defines a dictionary.

“dictionary[key]! ” returns a value of the dictionary.

Modify Dictionary

The syntax to modify the value of a dictionary is:

dictionary[key] = newValue

Example 6.2

var myDict: [Int: String] = [1: "A", 2: "B", 3: "C"]

var oldVal = myDict[2]

myDict[2] = "New"      // modify the value

print( "key = 1, value is \(myDict[1]! )" )

print( "key = 2, old value is \(oldVal! )" )

print( "key = 2, new value is \(myDict[2]! )" )

print( "key = 3, value is \(myDict[3]    ! )" )

Output:

key = 1, value is A

key = 2, old value is B

key = 2, new value is New

key = 3, value is C

Explanation:

“myDict[2] = "New"” modifies the value of the dictionary as “New”

Remove a “Key : Value”

The syntax to remove a “key: value” is:

dictionary[key] = nil

After a “key: value” is removed, the compiler may show a warning message. (It depends on the different Swift version).

Example 6.3

var myDict: [Int: String] = [1: "A",  2: "B",  3: "C"]

myDict[2] = nil       // remove a key : value

print( "key = 1, value is \(myDict[1]! )" )

print( "key = 2, value is \(myDict[2])" )

print( "key = 3, value is \(myDict[3]    ! )" )

Output:

key = 1, value is A

key = 2, value is nil

key = 3, value is C

(warning message……)

Explanation:

“myDict[2] = nil” removed the “2: ’B’”, and the compiler may show a warning message. (It depends on the different Swift version).

Iterate Through Dictionary

The syntax to iterate through a dictionary is:

for (key, value) in dictionary {…}

Note: Dictionary is an unordered collection.

Example 6.4

var myDict: [Int: String] = [1: "A", 2: "B", 3: "C"]

for (key, value) in myDict {

print(" The key \(key) 's value is \(value)")

}

Output:

The key 1 's value is A

The key 2 's value is B

The key 3 's value is C

Explanation:

“for (key, value) in myDict {…}” iterates through the dictionary.

Note: Dictionay’s output is unordered.

How Many Key : Value

The syntax to count how many “key: value” in a dictionary is:

dictionary    . count

Example 6.5

var myDict1: [Int: String] = [1: "A", 2: "B", 3: "C"]

var myDict2: [Int: String] = [4: "D", 5: "E"]

print("myDict1 contains \(myDict1.count ) key/value pairs")

print("myDict2 contains \(    myDict2.count ) key/value pairs")

Output:

myDict1 contains 3 key/value pairs

myDict2 contains 2 key/value pairs

Explanation:

“myDict1. count” and “myDict2. count” counts how many key/value pairs in the dictionaries.

Create a Dictionary

The syntax to create an empty dictionary is:

var dictionary = [keyType    : valueType]()

Example 6.6

var myDict = [Int: String]()      // create a dictionary

myDict[1] = "Rust "     // assign a value to the dictionary

myDict[2] = "in "

myDict[3] = "8 Hours"

print("\(myDict[1]! )\(myDict[2]! )\(myDict[3]! )")

print("Is myDict empty?  \(    myDict.isEmpty )")   // check

Output:

Rust in 8 Hours

Is myDict empty?  false

Explanation:

“var myDict = [Int: String]()” creates an empty dictionary.

myDict[1] = "Rust " assigns a value to the empty dictionary.

“myDict. isEmpty” checks if the dictionary is empty.

Functions

A function is a code block that can repeat to run many times. To define a function, use “func functionName ( ) { }”.

func funcName ( ) { }

To call a function, use “functionName ( )”

funcName ( )

Example 6.7

func title ( ) {     // define a function “title”

print ("Java in 8 Hours")

}

title ( )      // call the function “title”

Output:

Java in 8 Hours

Explanation:

“func title()” defines a function “title”.

“title()” calls the function “title”.

Return Value

“return” command is used to return its value to the caller of the function.

func funcName -    > returnType ( ) { return … }

Example 6.8

func title() -> String {

return "Java in 8 Hours"    // return the value to the caller

}

print(title())         // call the function “title”

Output:

Java in 8 Hours

Explanation:

“return” command is used to pass its value to the caller, just like assigning the value “Java in 8 Hours” to the caller “title()”.

“title()” is a caller of the function.

Function with Parameter

The syntax to define a function with a parameter is:

func funcName(parameter) -    > returnType{ return }

The syntax to call a function with parameter is:

funcName (parameter)

Example 6.9

func title ( book : String ) -> String {

return ( book )

}

print ( title (     book : "R in 8 Hours" ))   // pass the parameter

Output:

R in 8 Hours

Explanation:

“book : String” is a String type parameter, which is used to receive the parameter value.

“title( book : "R in 8 Hours")” calls the function “title”, and passes the parameter value to the function.

Vary Type  Parameters

The type of parameters may be different from the caller.

The syntax to define a function with different type parameter is:

func funcName     <Type> ( parameters: Type... ) {     }

The above can apply to the function containing different type parameters.

Example 6.10

func myFunc<Type>( paras: Type... ){

for val in paras{

print(val)

}

}

myFunc(paras: 100, 200, 300)     // Int type

myFunc(paras: 0. 1, 0. 2, 0. 3)     // Float type

myFunc(paras    : "Go ", "in ", "8 Hours")     // String type

Output:

100

200

300

0. 1

0. 2

0. 3

Go

in

8 Hours

Explanation:

“func myFunc<Type>( paras: Type... ){   }” defines a function that can deal with various type parameters.

The type of the parameters includes Int type, Float type, and String type.

Default Parameters

The parameters of a function can be set up a default value.

func funcName (    variable: type = value )

If a function is called without parameters, then the default parameters will work.

Example 6.11

func member (name : String, age: Int = 18 , height: Float = 6.9 ) {

print("name: \(name)  age: \(age)  height: \(height)")

}

member(name: "Andy", age: 16, height: 7. 2)

member(name    : "Mike")

Output:

name: Andy  age: 16  height: 7. 2

name: Mike  age: 18  height: 6. 9

Explanation:

“name : String, age: Int = 18 , height: Float = 6. 9” is the default parameters.

Hour 7

Class/Object

Closures

Closures are the blocks which contain a particular functional code. It is a little bit like an anonymous function.

The syntax to define a closure is:

let constant = {…}      or     var variable = {…}

The {…} is a closure.

The syntax to call a closure is:

constant()      or      variable()

Example 7.1

let book = { print("PHP in 8 Hours") }

book()

Output:

PHP in 8 Hours

Explanation:

“{ print("PHP in 8 Hours") }” defines a closure.

“book()” calls the closure.

Closure with Parameters

The syntax of a closure with parameter is:

{(parameters) -    > returnType in……}

Example 7.2

var add = {(n1: Int, n2: Int) -> Int in     // closure

return ( n1 + n2 )

}

var sum = add(10, 20)     // call the closure

print ( sum )

Output:

30

Explanation:

The above example defines a closure with parameters.

The closure is always defined by a { }.

Enumeration

An enum type provides a well-organized way to define a set of named integral constants that may be assigned to a variable.

The syntax to declare an Enumeration is:

enum enumName {

case member1

case member2

case member3

}

“enum enumName{ }” defines an enumeration.

“member1, member2, member3” is three enum members.

Example 7.3

enum Today {      // define a enum “Today”

case Morning      // enum member

case Afternoon

case Evening

}

The syntax to access the enumeration member is:

enumName    . member

Example 7.4

enum Today {    // define an enumeration

case Morning     // define an enum member

case Afternoon

case Evening

}

var dayTime = Today.Afternoon      // access a member

switch dayTime {

case Today. Morning:

print("It is Morning now. ")

case Today. Afternoon:

print("It is Afternoon now")

case Today. Evening:

print("It is Evening now")

}

Output:         It is Afternoon now

Explanation:

“enum Today {…}” defines an enumeration “Today”.

“Today. Afternoon” access the member “Afternoon”.

Structure

A struct type is a value type that is typically used to encapsulate small groups containing related variables.

The syntax to declare a struct type is:

struct structName {

member 1

member 2

member 3

}

“struct structName{ }” defines a structure

“member1, member2, member3” is three struct members.

Example 7.5

struct Car {     // defines a structure

var speed1 = 68     // structure member

var speed2 = 70

var speed3 = 82

}

The syntax to access the structure member is:

structName( )    . member

Example 7.6

struct  Car {    // define a structure

var speed1 = 68

var speed2 = 70

var speed3 = 82

}

print("Speed1 is \(Car().speed1 ) miles/hr")

print("Speed2 is \(Car().speed2 ) miles/hr")

print("Speed3 is \(    Car().speed3 ) miles/hr")

Output:

Speed1 is 68 miles/hr

Speed2 is 70 miles/hr

Speed3 is 82 miles/hr

Explanation:

“struct  Car {…}” defines a structure “Car”

“Car(). speed1” accesses the member “speed1”.

Class

A class is a template for an object, and creates an object.

The syntax to create a class is:

class ClassName {

member 1

member 2

……

member n

}

A class always includes some members.

Example 7.7

class Fruit {      // create a class “Fruit”

var color: String       // member

var size: String

var price: Int

}

Note: the class name usually should be capitalized.

Object

Object is an instance of a class.

The syntax to create an object is:

var obj = ClassName ( )     // create an object “obj”

obj. member 1       // an object references a member

obj. member 2

obj    . member n

The object need to use dot symbol to reference a member.

Example 7.8

var apple = Fruit()      // create an object “apple”

apple. color        // object reference member

apple. size

apple    . price

Sometimes the object needs to reference a function by using dot symbol, the syntax is as follows:

obj    . myFunc()

Class & Object

Example 7.9

class Fruit {     // create a class "Fruit"

var color: String = "Red"

var size: String = "Big"

var price: Int = 100

}

var apple = Fruit()    // create an object "apple"

print("The apple's color is \(apple.color )")

print("The apple's size is \(apple.size )")

print("The apple's price is $\(    apple.price )")

Output:

The apple's color is Red

The apple's size is Big

The apple's price is $100

Explanation:

“class Fruit {…}” creates a class “Fruit”.

“var apple = Fruit()” creates an object "apple"

“apple. color” means “ apple’s color ”.

Property

A variable in a class is called as “property”, which can be modified by assigning a new value.

obj    . property = value

Example 7.10

class Fruit {

var price: Int = 100    // initialization

}

var apple = Fruit()

apple.price = 200      // modify the property value

print("The apple's price is $\(apple    . price)")

Output:

The apple's price is $200

Explanation:

“apple. price = 200” modifies the property value of the object.

Method

A function in a class is called as “method”, which can be referenced by an object.

obj    . methodName( )

Example 7.11

class Fruit {

var size: String = "Big"

func meth() {        // define a method

print ("That is a \(size) Apple! ")

}

}

var apple = Fruit()

apple.meth()        // reference the method

Output:

That is a Big Apple!

Explanation:

“func  meth() {.. }” defines a method.

“apple. meth()” references the method.

Modify a Method

The variable in a method can by modified by using “let”.

let constant = value

Example 7.12

class Fruit {

var size: String = "Big"

func meth() {

let size = "Small"      // modify the property value

print ("This is a \(size) Apple! ")

}

}

var apple = Fruit()

apple    . meth()

Output:

This is a Small Apple!

Explanation:

“let size = "Small"” modifies a property value in a method.

Hour 8

Operations

Inheritance

Inheritance means that a child class can use the methods and properties in a parent class .

Namely, the child class can call and access methods and properties of the parent class .

The syntax of inheritance is :

class ChildClass : ParentClass {…}

Example 8.1

class Book{         // parent class

func show(){

myBook . title()

}

}

class eBook : Book{       // inheritance

func title(){

print("C# in 8 Hours")

}

}

let myBook = eBook()    // create an object of the child class

myBook.show()       // call the method in the parent class

Output:

C# in 8 Hours

Explanation:

“class Book{…} ” creates a parent class.

“class eBook : Book{…} ”: a child class inherits a parent class.

“myBook . show() ”: an object of the child calls a method of the parent class.

“myBook . title() ” calls the method in the child class.

Parent class is also known as “super class”.

Child class is also known as “sub class”.

Overriding

The method of child class can override the method of the parent class, if the method name and argument are the same.

The syntax of overriding is:

override func child-method() {…}

Example 8.2

class ParentClass {

func display() {

print("Parent Class in here")

}

}

class ChildClass: ParentClass  {

override func display() {      // overriding

print("Child Class in here")

}

}

let parentObj = ParentClass()

parentObj. display()

let childObj = ChildClass()

childObj    . display()

Output:

Parent Class in here

Child Class in here

Explanation:

There is a method “display()” in both parent class and child class. By using a keyword “override”, the display() in child class can override the display() in the parent class.

“override func display() {…}” can override the method in the parent class.

Initializer

The initializer is used to initialize each property of the class by using “init()”, the syntax of the initializer is as follows:

init() {…}

Example 8.3

class square {

var length: Int

var width: Int

init() {      // initializer

length = 100      // initialization

width = 100

}

}

var area = square()

print("The area of the square is    : \( area. length*area. width)")

Output:      The area of the square is: 10000

Explanation:

“init() {…}” initializes each property value of the class.

Self

In the initializer, the keyword “self” represents the current object. “self” is used to initialize each property of the class.

self    . property = value

Example 8.4

class addition {

let a: Int

let b: Int

let sum: Int

init(a: Int, b: Int) {

self.a = a      // self represents the current object

self.b = b

sum = a + b

print("20 + 80 = \(sum)")

}

}

let obj = addition(a    : 20, b: 80)

Output:     20 + 80 = 100

Explanation:    “self. a = a” initializes the property “a”.

Deinitializer

When  an object is removed, the deinitializer will be executed to free resources. The syntax of deinitializer is:

deinit {    ... }

Example 8.5

class Students {

var name: String

init(name: String) {

self. name = name

print("The boy's name is \(name)")

}

deinit {      // deinitializer

print("The boy was dismissed from his school")

}

}

var boy: Students? = Students(name: "Tomy")

boy = nil     // remove an object and execute the deinit

Output:

The boy's name is Tomy

The boy was dismissed from his school

Explanation:

“var boy: Students? = Students(name: "Tomy")” creates an object “boy”, the parameter is “name, Tomy”.

“Students?” means that the data type is optional. Its variable value “boy” may be equal to nil, so its data type needs a “? ”.

“boy = nil” removes the object “boy” and executes the deinit{…}. The deinitializer will free the resource and show a message.

Subscript

The keyword “Subscript” is used to process the index of an array, and accesses and assigns an instance with an index value.

The syntax of the subscript is as follows:

subscript(index: Int) -> Type {

set(newValue) {    // assign value

}

get {    // return the value to the caller

}

}

Example 8.6

class OneDay {

var day = ["Morning", "Afternoon", "Evening"]

// "day" includes three "dayValues"

subscript(key: Int) -> String {    // process "key"

set(dayValues) {

self. day[key] = dayValues    // assign dayValues

}

get {

return day[key]    // return dayValues to the caller

}

}

}

var d = OneDay()   // create an object

print(d[0])

print(d[1])

print(d[2])

Output:

Morning

Afternoon

Evening

Explanation:

“subscript(key: Int) -> String {…}” is used to precess the index of an array.

“key” is the index of the array.

“dayValues” means Morning, Afternoon, Evening.

set(dayValues) is equal to set(Morning, Afternoon, Evening).

d[0], d[1], d[2] accesses day[key] respectively.

Data Type Conversion

The keyword “as” is used to convert the data type.

The syntax to convert a data type is:

value as newType

Example 8.7

var num1 = 100 as Double

var num2 = 10 as Float

var num3 = (100 / 3) as Int

print (num1)

print (num2)

print (num3)

Output:

100. 0

10. 0

33

Explanation:

“100 as Double” converts the type of 100 as Double type.

Underline

The underline “_” is used to ignore a value or a parameter name.

“_” means “ignore”.

Example 8.8

var base = 2

var power = 3

var num = 1

for _ in 1... power {     // using “_” to ignore the item on “_”

num *= base

}

print("\(base) to the power of \(power) is \(num)")

Output:

2 to the power of 3 is 8

Explanation:

“for _ in 1... power”: The “_” means that the item on “_” is no longer used.

Q & A

Questions

Please choose the correct answer.

01.

// Please fill in a symbol

var str = "Hello! " fill in print(str)

A. ,

B. .

C. !

D. ;

02.

fill in miles = Int     // define an alias of Int

var highway: miles = 200

print(highway)

A. typealias

B. type

C. alias

D. typename

03.

var myVar:String?

myVar = "Rust in 8 Hours"

print( myVar fill in )     // Please fill in a symbol

A. ,

B. .

C. !

D. ;

04.

\b makes a backspace

fine in makes an output to the next new line.

\r makes a return

\t makes a tab

A. \l     B. \m      C. \n      D. \o

05.

var str = "POWERSHELL"

print( "The length of \(str) is: " )

print( "\(str. fill in )" )      // get the length of the string

A. length

B. count

C. size

D. length()

06.

var myDict:[Int:String] = [1:"A",  2:"B",  3:"C"]

print( "key = 1, value is \(myDict[1] fill in )" )  // fill in a symbol

print( "key = 2, value is \(myDict[2] fill in )" )

print( "key = 3, value is \(myDict[3] fill in )" )

A. ,

B. .

C. !

D. ;

07.

The syntax of a closure with parameter is:

{(parameters) -> returnType fill in ……}

A. on

B. at

C. by

D. in

08.

The syntax of inheritance is:

class ChildClass fill in ParentClass {…}

A. inherit

B. :

C. extends

D. <

09.

"var" is used to declare a variable.

"fill in " is used to declare a constant.

A. let

B. con

C. const

D. final

10.

Which following variable name is invalid?

A. _invalid

B. non_variable

C. 100percentvalid

D. InvalidVariable.

11.

Using the “ fill in ” to get a nil value will cause a runtime error.

var myVar: String?

if myVar == nil {

print(myVar fill in )

}

A. ;

B. !

C. ?

D. $

12.

The keyword “fill in ” is used to continue to execute the next case statement, regardless of whether the condition is met or not.

switch ( variable ) {

case 1: if equals this case, do this

fill in

case n: must do the next one.

default : if not equals any case, run default code

}

A.   continue

B. break

C. return

D. fallthrough

13.

Which following command is correct to create an array?

A. var myArray: [type] = [val1, val2, val3, …]

B. var myArray: [type] = (val1, val2, val3, …]

C. var myArray: [type] = {val1, val2, val3, …}

D. var myArray: [type] = <val1, val2, val3, …>

14.

var myDict: [Int: String] = [1: "A",  2: "B",  3: "C"]

myDict[2] = fill in        // remove a key : value

print( "key = 1, value is \(myDict[1]! )" )

print( "key = 2, value is \(myDict[2])" )

print( "key = 3, value is \(myDict[3]! )" )

A. remove

B. delete

C. nil

D. eliminate

15.

fill in Fruit {      // create a class “Fruit”

var color: String       // member

var size: String

var price: Int

}

A. create

B. new

C. public

D. class

16.

fill in () {     // initializer

length = 100     // initialization

width = 100

}

A. initialize

B. init

C. initial

D. initialization

17.

print("Please enter your name: ")

if let name = fill in () {     // user-input function

print(name)

}

A. userInput()

B. input()

C. inputLine()

D. readLine()

18.

var title = "'R in 8 Hours'"

var author = "Ray Yao"

print("The author is fill in (author) ")

// outputs the variable value inside the double quotes .

A. /

B. \

C. $

D. !

19.

var string1: String = "computer language: "

var letter2: Character = "R"

string1. fill in ( letter2 )     // append letter2 to string1

print("Learn a \(string1)")

A. append()

B. add()

C. join()

D. connect()

20.

What is the output according to the following code?

var num = 0

while num < 10 {

if num == 8 {

break    // leave the while loop

}

num = num + 1

}

print( num )

A. 6

B. 7

C. 8

D. 9

21.

var array1: [Int] = [100, 101, 102]

var array2: [Int] = [900, 901]

var array3 = array1 fill in array2    // merge two arrays

for element in array3 {

print(element)

}

A. +

B. －

C. *

D. /

22.

The syntax to define a function with different type parameter is:

func funcName fill in Typefill in ( parameters: Type... ) {     }

A. [   ]

B. {   }

C. (   )

D. <   >

23.

var apple = Fruit()      // create an object “apple”

apple fill in color        // object reference member

apple fill in size

apple fill in price

A. ,

B. .

C. !

D. ;

24.

class addition {

let a: Int

let b: Int

let sum: Int

init(a: Int, b: Int) {

fill in .a = a      // a keyword represents the current object

fill in .b = b

sum = a + b

print("20 + 80 = \(sum)")

}

}

let obj = addition(a: 20, b: 80)

A. obj

B. object

C. myObj

D. self

Swift Source code download link:

https : //forms . aweber . com/form/22/1538006522 . htm

Answers

01    . D

09    . A

17    . D

02    . A

10    . C

18    . B

03    . C

11    . B

19    . A

04    . C

12    . D

20    . C

05    . B

13    . A

21    . A

06    . C

14    . C

22    . D

07    . D

15    . D

23    . B

08    . B

16    . B

24    . D

Source Code Download

Swift Source code download link:

https : //forms . aweber . com/form/22/1538006522 . htm

Perl

Hour 1

Introduction

What is Perl?

Perl is an abbreviation for “Practical Extraction Report Language”.

Perl language is an interpreted scripting language, which was developed by Larry Wall in 1986 as a scripting language designed to handle system-oriented tasks in Unix environments. Perl has a strong ability to transform files and characters, it is especially suitable for tasks related to system management database and network interconnection as well as WWW programming, which makes Perl the tool language of choice for system maintenance managers and CGI programmers.

Perl is a high-level, universal, literal, dynamic programming language.

The most important features of Perl are the built-in integration of regular expression capabilities, as well as the huge third-party code library CPAN.

Perl can easily do the following tasks: 1. Text data processing. 2. Network program processing. 3. Database processing. 4. XML document processing. 5. System maintenance processing. 6. Image processing.

Install Perl

Download Perl

The official download link of Perl is as follows:

http : //strawberryperl . com/

Install Perl

After downloading the Perl, Please double click it,  and start to install Perl by following the instruction of the installer.

Click “Next” button to install the Perl step by step……

When the installation is complete, please click the “Finish” button.

Create a Working Folder

In order to run Perl program easily, we can create a working folder in the root directory of C: disk. The working folder will be named “myPerl”. For example:

C:\myPerl

All Perl files will be saved in the working folder “myPerl”.

Run First Program of Perl

1. Click the Perl (Command Line) icon, open the Perl as follows:

2. Access the working folder “myPerl” in C: disk.

Please enter “cd C:\myPerl ”, specify the “myPerl” as a current working folder.

3. Open the Notepad, input the following Perl code to the Notepad editor.

# It will output "Hello, World"

print "Hello, world    ! ";

Save the file named “Hello.pl ” to the folder “myPerl ”.

4. In Perl (Command Line), enter “perl Hello.pl ” to execute this Perl program.

You can see the output: “ Hello, world! ”

Congratulation! Your first Perl program run successfully!

The syntax to run a Perl program with Command Line is as follows:

perl filename.pl

“. pl” is an extension name of Perl.

Perl Comment

#

# is used to single-line comment.

=pod

……

……

=cut

“=pod……=cut” is used to multi-line comment.

Example 1.1

print "Hello! ";  # single-line comment

=pod

multi-line comment

multi-line comment

multi-line comment

=cut

Output:       Hello!

Explanation:    The Perl interpreter will ignore the comments.

Data Type

Perl has various basic data types, such as variables, arrays, hashes, integer, floating point, and string.

1. Variable

The value of a variable may change at runtime.

The “$” symbol is used to declare a variable.

For example:   $myVariavle

2. Array

The array is a special variable, which contains a series of values.

The “@” symbol is used to declare an array.

For example:   @myArray

3. Hash

A hash is an unordered collection of key/value pairs.

The “%” symbol is used to declare a hash.

For example:   %myHash

4. Integer

Integer means the number without decimal places.

For example:   100

5. Floating Point

The floating point means the number with decimal places.

For example:   2 . 718

6 . String

The string consists of a series of characters, spaces and numbers .

A string is always enclosed with double quotes or single quotes .

For example :     “ myString ”

Example 1.2

$int = 100;      # define an integer

$str = " Good ";     # define a string

$flt = 2. 718;     # define a floating point

print $int, $str, $flt;

Output:      100 Good  2. 718

Explanation:

$int, $str and $flt are integer, string and floating point variables.

Escape Sequences

The “ \ ” backslash character can be used to escape characters.

\b makes a backspace

\n outputs content to the next new line.

\r makes a return

\t makes a tab

\’ outputs a single quotation mark.

\” outputs a double quotation mark.

Example 1.3

print("He said \" Hello \n World! \" ");

//  \” outputs a double quote

// \n outputs contents to a new line .

Output:

He said "Hello

World! "

Explanation:

\” outputs a double quotation mark.

\n outputs the contents into a new line.

Print

Print command is used to output contents.

print  “……”

print      ‘……’

print “ ……” will output an interpreted value or a calculated value by using double quotes.

print ‘ ……’ will output an original value by using single quotes.

Example 1.3

$score = 100;       # $score is a variable

print " $score \n" ;    # using double quotes

print     ' $score \n' ;    # using single quotes

Output:

100

$score \n

Explanation:

The contents inside the double quotes can be interpreted.

The contents inside the single quotes cannot be interpreted, the output is the original values.

Here Document

"Here Document" is used to define a series of texts and output multi-line texts.

The syntax of “Here Document” is as follows:

<< "Here";

……

Here

Example 1.4

$var = << "Here";

"Here Document" can define a series of texts. \n

"Here Document" can show multi-line texts.

Here

print "$var";

Output:

"Here Document" can define a series of texts.

"Here Document" can show multi-line texts.

Explanation:

“<<"Here";……Here” is a Here Document.

Identifier

An identifier is a name when the programmer writes the code.  The variable name, constant name, function name, block name used in the program are collectively referred to as identifiers.

For example:

The identifier $myVariable is a variable name.

The identifier @myArray is an array name.

The identifier %myHash is a hash name    .

The rule of the Perl identifier is as follows:

1. Identifiers consist of letters (a~z, A~Z), numbers (0~9) and underscores ( _ ).  e. g. $mark_10 is a variable name.

2. Identifiers begin with letters or underscores, and cannot begin with numbers.   e. g. $10score is an invalid variable name.

3. Identifiers are case sensitive.

e. g.   $myVariable and $MyVariable represent two different variable names.

Hour 2

Basics

Variable

The value of the variable is changeable at runtime.

“$” can be used to declare a variable. Its syntax is:

$variable = value

Variables do not need to declare a data type.

Example 2.1

$myVariable = "Hello, World! ";

print     $myVariable ;

Output:

Hello, World!

Explanation:

“$” is a variable symbol.

“myVariable” is a variable name.

In Perl, each instruction is ended with a semicolon (; ).

Constant

The value of the constant is unchangeable at runtime.

The syntax to define a constant is as follows:

use constant CONSTANT_NAME => value;

The constant name is usually capitalized.

Example 2.2

use constant MON => "Monday";

use constant SUN => "Sunday";

print MON . "\n";

print SUN     . "\n";

Output:

Monday

Sunday

Explanation:

“use constant MON” defines a constant name “MON”.

“use constant SUN” defines a constant name “SUN”.

“. \n” is used to output the string value in the next line.

String

The string consists of a series of characters, spaces, numbers.

The string is always enclosed by double quotes or single quotes.

The dot “. ” symbol can connect two strings.

Example 2.3

$str1 = "Shell Scripting" ;

$str2 = " in 8 Hours" ;

$myString = $str1 . $str2;

print $myString;

Output:

Shell Scripting in 8 Hours

Explanation:

"Shell Scripting" is a string enclosed by a double quote.

“$str1 . $str2” connects two strings by using a dot “. ” symbol.

Array

The array is a special variable that contains a series of values, the array can be a different data type.

The syntax to create an array is as follows:

@arrayName = (val1, val2, val3)

“val1, val2, val3” is three element values of the array.

The syntax to access an array element is:

$arrayName [index]

“index” is the element number, it begins with zero

Example 2.4

@book = ("Go", " in", " 8 Hours");     # create an array

print "$book[0]";       # the index is 0, accesses “Go”

print "$book[1]";       # the index is 1, accesses “in”

print "$book[2]";           # the index is 2, accesses “ 8 Hours”

Output:      Go in 8 Hours

Explanation:

“@book” is the name of the array, which contains three elements.

Element Range

The range (startValue .. endValue) can access all elements from the startValue to the endValue, its syntax is as follows:

(startValue     .. endValue)

“(startValue .. endValue)” represents all elements from startValue to endValue.

Example 2.5

@array1 = (0..8) ;         # create an array

@array2 = (A..N) ;        # create an array

print "@array1\n";     # output from 0 to 8

print "@array2\n";         # output from A to N

Output:

0 1 2 3 4 5 6 7 8

A B C D E F G H I J K L M N

Explanation:

“(0.. 8)” represents all elements from 0 to 8.

“(A.. N)” represents all elements from A to N.

Array Size

The syntax to get the size of an array is:

$size = @arrayName;

print $size

“@arrayName” can get the size of an array.

The value of $size will be the length of the array.

Example 2.6

@myArray=(1,2,3,4,5,6);

$len=@myArray ;

print "The size of myArray is     $len ";

Output:

The size of myArray is 6

Explanation:

“$len=@myArray;” assigns the value of myArray size to $len.

The First Element

The syntax to add an element to the beginning of an array is:

unshift(@array, newElement);

The syntax to remove the first element of an array is:

shift(@array);

Example 2.7

@arr = ("A","B","C");    # create an array

unshift (@arr, "OK");    # add an element "OK" to the beginning

print "  $arr[0]", "  $arr[1]", "  $arr[2]", "  $arr[3]";

print "\n";

shift (@arr);    # remove the first element "OK"

print "  $arr[0]", "  $arr[1]", "  $arr[2]";

Output:

OK  A  B  C

A  B  C

Explanation:

“unshift()” and “shift()” adds or removes the first element.

The Last Element

The syntax to add an element to the end of an array is:

push(@array, "newElement");

The syntax to remove the last element of an array is:

pop(@array);

Example 2.8

@arr = ("A","B","C");    # create an array

push(@arr, "OK") ;    # add an element "OK" to the end

print "  $arr[0]", "  $arr[1]", "  $arr[2]", "  $arr[3]";

print "\n";

pop(@arr) ;    # remove the last element "OK"

print "  $arr[0]", "  $arr[1]", "  $arr[2]";

Output:

A  B  C  OK

A  B  C

Explanation:

“push()” and “pop()” adds or removes the last element.

Extract Elements

The syntax to extract some elements from an array is:

@array[index1, index2, index3…];

“index1, index2, index3…” specifies the elements to extract by index.

Example 2.9

@arr1 = ("A","B","C", "D", "E", "F");

@arr2 = @arr1[1,3,5] ;     // extract elements by index

print @arr2;

Output:

BDF

Explanation:

“@arr1[1,3,5]” extracts the elements by index1, index3, index5, their values are B, D, F respectively.

By the way, you can also use Range to extract elements

For example: @myArray[index1 .. index2].

Sort Elements

The syntax to sort all elements of an array is:

sort(@array);

Example 2.10

# create an array

@arr = ("E","D","B", "F", "A", "C");

print "Before sorting: @arr\n";

@arr = sort(@arr) ;      # sort the array

print "Having sorted    : @arr\n";

Output:

Before sorting: E D B F A C

Having sorted: A B C D E F

Explanation:

“sort(@arr)” sorts all elements of the array.

Conversion

A string can be converted to an array, and an array can also be converted to a string.

@array = split('seperator', $string);   # convert string to array

$string = join( 'seperator', @arring );      # convert array to string

“seperator” can be a space, “*”, “-”, “#”, “@”……

Example 2.11

$myStr = "Hello My Friends";     # create a string

@arr = split (' ', $myStr);     # convert to array

$str = join ( '**', @arr );     # convert to string

print "$arr[0] $arr[1] $arr[2] \n";

print "$str\n";

Output:

Hello My Friends

Hello**My**Friends

Explanation:

“split()” can convert a string to an array.

“join()” can convert an array to a string.

Merge Arrays

The syntax to merge two arrays is as follows:

(@array1    , @array2)

Example 2.12

@arr1 = ("Shell", "Scripting");

@arr2 = ("in", "8", "Hours");

@mergeArr = (@arr1, @arr2) ;     // merge two arrays

print "@mergeArr";

Output:

Shell Scripting in 8 Hours

Explanation:

“(@arr1, @arr2)” merges two arrays.

Hour 3

Hash

Hash

A hash is a collection of “key/value”.  The symbol “%” is used to make a hash name. ${key} is used to access a hash element.

The syntax to create a hash is as follows:

%hash = ('key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3',...);

Example 3.1

%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');

print "$score{'60'}\n";

print "$score{'85'}\n";

print "$score{'100'}\n";

Output:

passed

ok

excellent

Explanation:

“%score = (…)” creates a hash with three elements.

"$score{'60'}” accesses the element whose key is 60.

Check Existing

The exists() function can check whether the key/value is existing, If a key/value pair does not exist, the “undefined” value is returned. The syntax to use the exists() is as follows:

exists($hash{'key'})

Example 3.2

%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');

if( exists($data{'90'} ) ){      # chick existing

print "The score 90 is $data{'90'} \n";

}

else{

print "The score 90 is not existing. ";

}

Output:

The score 90 is not existing.

Explanation:

“exists($data{'90'}” checks whether the key “90” and its value exist.

Get Hash Values

The syntax to get all values of the hash is as follows:

@array = values %hash

The above returns an array containing all values of the hash.

Example 3.3

%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');

@arr = values %score;   # get all element values of the hash

print "$arr[0]\n";

print "$arr[1]\n";

print "$arr[2]\n";

Outout:

passed

ok

excellent

Explanation:

The output is unordered.

“values %score” gets all the values of the hash “score”, and returns an array include these values.

Hash Size

The syntax to get the hash size is as follows:

@array = keys %hash;      # get all keys in the hash

$size = @array;            # get the total number of keys

Example 3.4

%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');

@arr = keys %score;

$size = @arr;

print "The total number of the keys is    : $size\n";

Output:

The total number of the keys is: 3

Explanation:

“@arr = keys %score;” gets all keys in the hash “score”, and returns an array including these keys.

“$size = @arr;” gets the total number of keys.

Add or Remove Element

$hash{'key'} = 'value';    # add a hash element

delete $hash{'key'};         # remove a hash element

Explanation 3.5

%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');

$score{'101'} = 'superhero!';      # add an element

delete $score{'60'};      # remove an element

@arr = values %score;

print "$arr[0] ";print "$arr[1] ";print "$arr[2] ";

Output:

ok   excellent   superhero

Explanation:

The output is unordered.

“$score{'101'} = 'superhero! ';” adds an element “superhero” to the hash.

“delete $score{'60'};” removes an element whose key is 60 in the hash.

Iterate Through Hash

foreach $key (keys %hash){

}

“foreach $key (keys %hash){…}” is used to iterate through the elements of the hash.

Example 3.6

%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');

foreach $key (keys %score){

print "$score{$key}\n";

}

Output:

passed

ok

excellent

Explanation:

“foreach $key (keys %score){…}” iterates through the elements of the hash “%score”.

Arithmetical Operators

Operators

Running

+

add or connect strings

-

subtract

*

multiply

/

divide

%

get modulus

**

power

Example 3.7

$a = 4; $b = 2;

$c = $a + $b;

print '$a + $b = ' . $c . "\n";     # output : $a + $b = 6

$c = $a * $b;

print '$a * $b = ' . $c . "\n";      # output : $a * $b = 8

$c = $a % $b;

print '$a % $b = ' . $c. "\n";     # output : $a % $b = 0

$c = $a ** $b;

print '$a ** $b = '     . $c . "\n";     # output : $a ** $b = 16

Comparison Operators

Operators

Running

Returns

>

greater than

true or false

<

less than

true or false

>=

greater than or equal

true or false

<=

less than or equal

true or false

==

equal

true or false

! =

not equal

true or false

For example:

$x=100;

$y=200;

($x == $y) returns false

($x != $y) returns true

($x >= $y) returns false

($x <= $y) returns true

Logical Operators

Operators

Result

and

If both operands are true, returns true

or

If one of the operands is true, returns true

not

If the operand is true, returns false

For example:

$x=true;

$y=false;

($x and $y) returns false

($x or $y) returns true

not ($x) returns false

not ($y) returns true

Assignment Operators

Operators

Examples:

Equivalent:

+=

x+=y

x=x+y

-=

x-=y

x=x-y

*=

x*=y

x=x*y

/=

x/=y

x=x/y

%=

x%=y

x=x%y

**=

x**=y

x=x**y

Example 3.8

$x = 100; $y = 200;

$y += $x; print "$y\n";     # $y=$y+$x   output : 300

$x = 100; $y = 200;

$y *= $x; print "$y\n";     # $y=$y*$x   output : 20000

$x = 100; $y = 200;

$y /= $x; print "$y\n";     # $y=$y/$x   output : 2

$x = 100; $y = 200;

$y     %= $x; print "$y\n";     # $y=$y%$x   output : 0

Dot Operators

Operators

Usage

Result

.

string     . string

connect two strings

..

num1     .. num2

from num1 to num2

Example 3.9

$x = "Very ";  $y = "Good! ";

$result = $x . $y ;

print "\$x . \$y = $result\n";

@result = (1..8) ;

print "(1    .. 8) = @result\n";

Output:

$x . $y = Very Good!

(1.. 8) = 1 2 3 4 5 6 7 8

Explanation:

“$x . $y ” connects two strings “Very” and “Good”.

“(1..8) ” returns a range from 1 to 8.

Increase & Decrease

++

add 1

- -

subtract 1

Example 3.10

$x= 100;

$x++ ;     # x increases 1

$result = $x ;

print "\$x++ = $result\n";

$y = 100;

$y- - ;     # y decreases 1

$result = $y ;

print "\$y-- = $result\n";

Output:      $x++ = 10

$y- - = 99

Explanation:

“$x++”     # x increases 1

“$y- -”     # y decreases 1

Hour 4

Statement

If Statement

if (boolean_expression){

# code

}

If the boolean expression returns true, the code within the if statement will be executed. If returns false, will not be executed.

Example 4.1

$num = 100;

if( $num < 200 ) {

printf "The num is less than 200\n";

}

Output:

The num is less than 200

Explanation:

Because “if($num<200)” returns true, the code within the “if statement” has been executed, and prints the result.

If-Else Statement

if (boolean_expression){

# code1

} else {

# code2

}

If the boolean expression returns true, the code1 within the if statement will be executed. If returns false, the code2 within the else statement will be executed.

Example 4.2

$num = 300;

if( $num < 200 ){

printf "The num is less than 200\n";

} else {

printf "The num is greater than 200\n";

}

Output:      The num is greater than 200

Explanation:

Because “if( $num < 200 )” returns false, the code within the else statement has been executed, and prints the result.

Unless Statement

unless(boolean_expression){

# execute when boolean_expression returns false

}

“unless(boolean_expression)” returns false, the code within the unless statement will be executed

Example 4.3

$num = 300;

unless( $num < 200 ) {

printf "The num is greater than 200\n";

}

Output:

The num is greater than 200

Explanation:

Because “unless($num<200)” returns false, the code within the unless statement has been executed, and prints the result.

Unless Statement

unless(boolean_expression){

# execute when boolean_expression returns false

} else {

# execute when boolean_expression returns true

}

“unless(boolean_expression)” returns false, the code within the unless statement will be executed. If returns true, the code within the else statement will be executed.

Example 4.4

$num = 100;

unless( $num < 200 ){

print "The num is greater than 200\n";

} else {

print "The num is less than 200\n";

}

Output:       The num is less than 200

Explanation:

Because “unless( $num < 200 )” returns true, the code within the else statement has been executed, and prints the result.

Ternary Operators

The ternary operators are “  ?  :   ”.

(boolean_expression)     ? code1 : code2;

If boolean_expression returns true, the code1 will be executed;

If boolean_expression returns false, the code2 will be executed.

Example 4.5

$score = 100;

$result = ($score >= 60 )? "passed" : "failed" ;

print "The examination is $result";

Output:

The examination is passed

Explanation:

Because ($score >= 60 ) returns true, “passed” has been executed.

The value of $result is passed.

While Loop

while(condition){

code;

}

The loop is executed when the condition is true, and exits when the condition is false

Example 4.6

$num = 1;

while( $num <= 8 ) {     # run 8 times

print "$num  ";

$num = $num + 1;

}

Output:

1  2  3  4  5  6  7  8

Explanation:

“while( $num <= 8 ) ” checks whether the condition is true, if the condition is false, the program exits the loop.

Do…While Loop

do{

code;

} while( condition );

Run the code first, then check whether the condition is true.

The loop is executed when the condition is true, and exits when the condition is false.

Example 4.7

$num = 1;

do {

print "$num  ";

$num = $num + 1;

}     while( $num <= 8 )      # run 8 times

Output:

1  2  3  4  5  6  7  8

Explanation:      Run the code within the do loop first, then:

“while( $num <= 8 ) ” checks whether the condition is true, if the condition is false, the program exits the loop.

Until Loop

until(condition){

code;

}

The loop is executed when the condition is false, and exits when the condition is true.

Example 4.8

$num = 1;

until( $num > 8 ) {     # run 8 times

print "$num  ";

$num = $num + 1;

}

Output:

1  2  3  4  5  6  7  8

Explanation:

Because until( $num > 8 ) returns false, the code within the until loop has been executed for 8 times, until the condition is true.

For Loop

for ( init; condition; increment ){

code;

}

The loop is executed when the condition is true, and exits when the condition is false

Example 4.9

for( $num = 1; $num <= 8; $num++ ) {

print "$num ";

}

Output:

1 2 3 4 5 6 7 8

Explanation:

“$num = 1” sets up the initial value.

“$num <= 8” sets up the condition of the loop.

“$num++” sets up the increment of each loop.

“for(…)” keeps looping until the condition is false.

Foreach Loop

foreach variable (list) {

code

}

“foreach loop” is used to iterate through all variable values in a collection.

Example 4.10

@myArray = (1, 6, 9, 8);

foreach $var (@myArray) {

print "$var ";

}

Output:

1 6 9 8

Explanation:

“foreach” statement iterates through all elements in the @myArray, assigns the values to the $var, and outputs its all values.

Continue

while(condition){

code1;

}continue{

code2;

}

The continue statement is used to continue next loop.

Example 4.11

$num = 10;

while($num <= 15){

print "$num  ";

} continue {

$num = $num + 1;

}

Output:

10  11  12  13  14  15

Explanation:

“continue { $num = $num + 1;}” continues running next while loop after the current block.

Last

last;

The last statement is used to exit the loop block, end the loop.

Example 4.12

$num = 10;

while( $num < 18 ){

if( $num == 15){  last; }

$num++;

print "$num  ";

}

Output:

11  12  13  14  15

Explanation:

“if( $num == 15){  last; }” exits the loop block when $num is 15.

Hour 5

Operations

Local & Greenwich Time

localtime()       # returns a local time

gmtime()       # returns a Greenwich time

time()         # returns the seconds accumulated since 1/1/1970

Example 5.1

$local_time = localtime() ;

print "The local time is: $local_time\n";

$grw_time = gmtime() ;

print "The Greenwich time is: $grw_time\n";

$epoc = time() ;

print "The cumulative seconds since 1/1/1970 is    : $epoc\n";

Output:

The local time is: Tue Oct 13 15: 11: 30 2020

The Greenwich time is: Tue Oct 13 19: 11: 30 2020

The cumulative seconds since 1/1/1970 is: 1602618009

Explanation:

localtime() returns a local time, gmtime() returns a Greenwich time, time() returns the seconds accumulated since 1/1/1970.

Subprogram

Subprogram is a function in Perl, it can be used repeatedly.

1. The syntax to define a subprogram is:

sub subName{     # subprogram is a function in Perl

}

2. The syntax to call a function is:

subName();

Example 5.2

sub book {    # define a subprogram

print "Scala in 8 Hours! ";

}

book() ;    # call the subprogram

Output:

Scala in 8 Hours!

Explanation:

“sub book{…} ” defines a subprogram “book”.

“book() ” calls the subprogram “book”.

Subprogram With Parameters

1. The syntax to define a subprogram is:

sub subName{

code @_        # @_ accepts all come-in parameters

}

@_[0] represents the number 0 parameter.

@_[1] represents the number 1 parameter.

@_[2] represents the number 2 parameter.

2. The syntax to call a function is:

subName(    parameters );

Example 5.3

sub books{

print "All books are :   @_ \n";

print "$_[0] in 8 Hours\n";

print "$_[1] in 8 Hours\n";

print "$_[2] in 8 Hours\n";

}

books("C#", "GO", "VB") ;

Output:

All books are :   C# GO VB

C# in 8 Hours

GO in 8 Hours

VB in 8 Hours

Explanation:

Subprogram is a function in Perl.

“books("C#", "GO", "VB");” calls the subprogram “books” with parameters “C#, GO, VB”

“@_” represents all come-in parameters.

@_[0] represents the number 0 parameter C#.

@_[1] represents the number 1 parameter GO.

@_[2] represents the number 2 parameter VB.

Return

“return” command is used to return its value to the caller.

return

Example 5.4

sub addition{

$sum = $_[0]+$_[1];

return $sum ;     # return its value to the caller

}

print addition(10, 20)         # caller

Output:

30

Explanation:

“return $sum ” returns its value to the caller “addition(…)”, just like “addition(10, 20) = $sum;”

Public & Private Variable

The variable defined outside a working scope is a public variable.

The variable defined inside a working scope is a private variable.

Working scope means a {…} range of a function, if, while, for, foreach. A private variable is invisible outside the working scope.

my $variable      #  “my” defines a private variable

Example 5.5

$var = "Public String" ;     # define a public variable

sub show{

my $var = "Private String" ;     # define a private variable

print "$var\n";     # print private variable

}

print "$var\n";      # print public variable

show();

Output:       Public String

Private String

Explanation:

$var = "Public String" is a public variable outside “sub show{}”

my $var = "Private String" is a private variable in “sub show{}”

Static Variable

Static variable makes its value last. Once a static variable is assigned a value, its value will persist until this static variable is given a new value .

use feature 'state';   # import ‘state’ before using static

state $variable;       # define a static variable

Example 5.6

use feature 'state' ;     # import ‘state’ feature

sub show{

state $number ;    # define a static variable

$number++;

print "$number  ";

}

for (0    .. 7){  show(); }     # call show() 7 times

Output:        1  2  3  4  5  6  7  8

Explanation:

“state $number;” defines a static variable, its value will last until being updated.

Reference

The reference is a pointer, which points to a variable, array, hash, subprogram. The value of a reference is a memory address.

By using a “\”, we can create a reference like this:

$var = \ $variable;     # variable reference

$arr  = \ @array;    # array reference

$ha   = \ %hash;     # hash reference

$sub   =     \ &subprogram;     # subprogram reference

Example 5.7

$var = "ok";

$v = \$var;      # reference

print "$v\n";

@arr = (10, 20, 30);

$a = \@arr;      # reference

print "$a\n";

Output:      SCALAR(0x55f27b7c29f8)

ARRAY(0x55f27b7c2ab8)

Explanation:

“$v = \$var; ” defines a variable reference.

“$a = \@arr; ” defines an array reference.

Cancel Reference

By adding a symbol $, @, %, & before a reference, we can cancel the reference.

$ $var       # cancel reference

@ $arr     # cancel reference

% $ha       # cancel reference

& $sub     # cancel reference

Example 5.8

$var = "ok";

$v = \$var;

print "$$v\n ";      # cancel reference

@arr = (10, 20, 30);

$a = \@arr;

print "    @$a\n ";     # cancel reference

Output:       ok

10 20 30

Explanation:

"$ $v\n" cancels reference by adding a $ before the reference.

"@ $a\n" cancels reference by adding a @ before the reference.

Format Output (1)

We can use “format ” to format the contents, and use “write ” to output the formatted contents.

The syntax to define a format contents is as follows:

format STDOUT =

# define a format contents

.

The syntax to output a formatted contents is as follows:

write;         # output the formatted contents

Example 5.9

format STDOUT =

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

"In 8 Hours" Programming

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.

write;

Output:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

"In 8 Hours" Programming

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Explanation:

“format STDOUT =    . ” defines a format contents.

“write;” outputs the formatted contents.

Format Output (2)

We can use “format ” to format the contents, and use “write ” to output the formatted contents.

The syntax to define a format contents is as follows:

format myFormat =

# define a format contents named “myFormat”

.

The syntax to output a formatted contents is as follows:

$~ = "myFormat";     # reference the myFormat

write;         # output the contents of $~

Example 5.10

format myFormat =

**********************************

"In 8 Hours" Series Books

**********************************

.

$~ = "myFormat";

write;

Output:

**********************************

"In 8 Hours" Series Books

**********************************

Explanation:

“format myFormat =     . ” defines a format content.

“myFormat” is a name of the format contents.

“$~ = "myFormat ";” specifies the format contents to be used.

“write;” outputs the formatted contents.

Hour 6

Files

Open a File

The syntax to open a file is as follows:

open( DATA, ‘mode’, ‘myfile    . txt’) or die $! ;

“DATA” is the file handle, which is used for I/O connection.

“mode” is a command to open a file in a specified way.

“die $! ”        shows a warning if fail to process the file.

The mode to open a file is as follows:

Mode

Description

<   or   r

read only

>   or  w

write only

>>   or   a

append

+<   or  r+

read or write

+>  or   w+

write or read

+>>    or   a+

append (write or read)

For example:

“open(DATA, ‘ < ’,  ‘myfile.txt’) or die $!; ” means that open the “myfile. txt” in read-only mode.

Write to File

The syntax to write to file is as follows:

print  DATA  $contents;

“$contents” is something that needs to write to a file.

Example 6.1

my $str = "Rust in 8 Hours";     # the contents to write

my $f = 'C: \myPerl\myfile. txt';      # the path to write

open(DATA, '>', $f) or die $! ;

print DATA  $str;      # write the contents to myfile . txt

close(DATA);     # close the file

print "Write to myfile    . txt successfully! \n";

Output:

Write to myfile. txt successfully!

Explanation:

Please check ‘'C: \myPerl\myfile. txt'’, you can find the contents “Rust in 8 Hours” in myfile. txt.

“print DATA  $str;” writes the contents to myfile. txt.

Read from File

The syntax to read contents from a file is as follows:

while(<DATA>){

print $_;

}

“$_” represents all contents in the file.

Example 6.2

my $f = 'C: \myPerl\myfile. txt';     # the path & file to read

open(DATA, '<', $f) or die $! ;

while(<DATA>){

print $_;      # read all contents from myfile . txt

}

print "\nRead a file successfully! ";

close(DATA);         # close the file

Output:

Rust in 8 Hours

Read a file successfully!

Explanation:

“while(<DATA>){ print $_; } ” reads contents from myfile. txt.

Input by User

The syntax to input data from a user to a file is as follows:

$data = <STDIN>;

Example 6.3

print "What is your name?\n";

$data = <STDIN> ;

print "My name is    : $data\n";

Output:

What is your name?

Ray Yao

My name is: Ray Yao

Explanation:

“$data = <STDIN>; ” is used to input data by users.

STDIN, STDOUT, and STDERR represent standard input, standard output, and standard error respectively.

File Copy

The syntax to copy a file is as follows:

while(<DATA1>){     # copy data1 to data2

print DATA2 $_;

}

Example 6.4

open(DATA1, '<', 'C: \myPerl\myfile. txt');     # open an old file

open(DATA2, '>', 'C: \myPerl\ourfile. txt');     # open a new file

while(<DATA1>){      # copy

print DATA2 $_;

}

print "Copy a file successfully! ";

close( DATA1 );

close( DATA2 );

Output:

Copy a file successfully!

Explanation:

Please check 'C: \myPerl\ourfile. txt'.

DATA1 represents file1, DATA2 represents file2.

File Rename

The syntax to rename a file is as follows:

rename ( file1, file2 );

Change the name of file1 to file2.

Example 6.5

my $file1 = 'C: \myPerl\myfile. txt';

my $file2 = 'C: \myPerl\yourfile. txt';

rename ( $file1, $file2 );

print "Rename a file successfully    ! ";

Output:

Rename a file successfully!

Explanation:

Please check 'C: \myPerl\yourfile. txt'.

“rename ( $file1, $file2 );” rename the “myfile. txt” as “yourfile. txt”.

File Remove

The syntax to remove a file is as follows:

unlink ( file );

Example 6.6

my $file = 'C: \myPerl\ourfile. txt';

unlink ( $file ) ;

print "Remove a file successfully    ! ";

Output:

Remove a file successfully!

Explanation:

Please check 'C: \myPerl\ourfile. txt', which is no longer existing.

“unlink ( $file ) ;” removes the “ourfile. txt”.

File Information

“_ _” can return the information of a file.

_ _FILE_ _  returns the current file name

_ _PACKAGE_ _  returns the package name of the file

Note: “_ _” is two underlines.

Example 6.7

print "The file name is : " . __FILE__ . "\n";

print "The package name is     : " . __PACKAGE__ . "\n";

Please save this file and its name as “myScript. pl”

Output:

The file name is : myScript. pl

The package name is : main

Explanation:

_ _FILE_ _  returns the current file name.

_ _PACKAGE_ _  returns the package name of the current file.

Directory Operation

The standard commands to process a directory is as follows:

Commands

Operations

opendir

open a dirctory

readdir

read a directroy

mkdir

create a directory

chdir

specify a current directory

rmdir

remove a directory

telldir

return the position of the current directory

seekdir

return the position of the specified directory

closedir

close a directory

Create a Directory

The syntax to create a directory is as follows:

mkdir( “ path / directory ”);

Create a new directory under the specified path.

Example 6.8

$d1 = "/myPerl/Directory1";

$d2 = "/myPerl/Directory2";

mkdir( $d1 ) or die "$! ";

mkdir( $d2 ) or die "$! ";

print "Create two directories successfully    ! \n";

Output:

Create two directories successfully!

Explanation:

Please check the directories “C: \myPerl”, you will find that two new directories “Directory1” and “Directory2” have been created.

“mkdir( $d1 ) ” creates a “Directory1” under “C: \myPerl”.

“mkdir( $d2 ) ” creates a “Directory2” under “C: \myPerl”.

Open & Read a Directory

The syntax to open or read a directory is as follows:

opendir (DIR, ‘ \directory ’);     # open a directory

read DIR         # read the directory

Example 6.9

opendir (DIR, 'C:\myPerl') or die $! ;

while ($contents = readdir DIR ) {

print "$contents\n";     # show anything under \myPerl

}

closedir DIR;

Output:

Directory1

Directory2

……

Explanation:

“opendir (DIR, 'C: \myPerl')” opens the directory “\myPerl”.

“readdir DIR” reads the directory “\myPerl”.

Change & Remove a Directory

The syntax to change or remove a directory is as follows:

chdir( ‘\directory’ );      # change as the current directory

rmdir( ‘\directory’ );          # remove the specified directory

Example 6.10

$d1 = "/myPerl/Directory1";

chdir( $d1 ) or die \$! ;     # specify the current directory

print "The directory you are in is $d1\n";

$d2 = "/myPerl/Directory2";

rmdir( $d2 ) or die $! ;      # remove the specified directory

print "Remove Directory2 successfully    ! \n";

Output:

The directory you are in is /myPerl/Directory1.

Remove Directory2 successfully!

Explanation:

“chdir( $d1 )” specifies Directory1 as the current directory.

“rmdir( $d2 )” removes Directory2.

Please check “C: \myPerl”, you cannot find Directory2 now.

Hour 7

Functions

Die Function

When an error happens, “die function” stops the running program, and outputs the error messages.

die “ error message ”, $    ! ;

Example 7.1

open(DATA,"<", abc. txt)

or die "Error! Cannot open abc.txt! \n", $! ;

# assume that there is no abc . txt

# in the current directory .

close(DATA);

Please Save the file as “test01.pl ” in “C: \myPerl”, and run it.

Output:

Error! Cannot open abc. txt!

No such file or directory at test01. pl line 1.

Explanation:

Because there is no “abc. txt” in the current directory, “die()” stopped the running program, and outputs the error message.

Warn Function

When an error happens, “warn function” outputs the warning messages.

warn " warning message ";

Example 7.2

open(DATA,"<", abc. txt)

or warn "Warning: Cannot open abc.txt!" ;

# assume that there is no abc . txt

# in the current directory .

close(DATA);

Please Save the file as “test02.pl ” in “C: \myPerl”, and run it.

Output:

Warning: Cannot open abc. txt! at test02. pl line 1.

Explanation:

Because there is no “abc. txt” in the current directory, “warn()” outputs the warning message.

Sysopen Function

Sysopen function is used to open a file in different modes.

The syntax of sysopen() is:

sysopen( DATA, "file    . txt", mode );

The usage of the parameter “mode” is as follows:

Modes

Open the file for this purpose:

O_RDWR

read or write

O_RDONLY

read only

O_WRONLY

write only

O_CREAT

create a file

O_APPEND

append a file

O_EXCL

check whether the file exists

For example:

sysopen (DATA, "myfile. txt", O_WRONLY);

# open a file “myfile . txt”, for writing only .

Match Operator

Match operator is used to check if a string contains a substring.

=~ /…/       # check whether some characters match

!~ /.../       # check whether no characters match

Example 7.3

$book = "Kotlin in 8 Hours";

if ( $book =~ /8 Hours/ ){      # check match

print "Some words match '8 Hours' \n";

}

if ( $book !~ /8 Hours/ ){      # check doesn’t match

print "No words match '8 Hours' \n";

}

Output:

Some words match '8 Hours'

Explanation:

“$book =~ /8 Hours/” checks whether some words in the $book match “8 Hours”.

“$book ! ~ /8 Hours/” checks whether no words in $book match “8 Hours”

RegExp Variable

There are three RegExp variables that can match different strings.

$`    # gets the previous substring of the matching string

$&    # gets the matching string

$'    # gets the following substring of the matching string

Note: The symbol of $` is different from $'

Example 7.4

$str = "HTML CSS in 8 Hours";

$str =~ /CSS/;

print "The previous string:   $` \n";

print "The matching string:   $& \n";

print "The following string    :   $' \n";

Output:

The previous string:   HTML

The matching string:   CSS

The following string:    in 8 Hours

Explanation:       $`, $&, $' return the previous string, the matching string, and the following string respectively.

Substitute Operator

The syntax to substitute a string1 as a string2 is as follows:

=~ s / string1 / string2 /;

“s” is a substitute operator parameter.

Example 7.5

$str = "Visual C# in 8 Hours";

$str =~ s/C#/Basic/ ;      # substitution

print "$str\n";

Output:

Visual Basic in 8 Hours

Explanation:

“=~ s / C# / Basic /;” substitutes the substring1 “C#” as the substring2 “Basic”.

Lowercase & Uppercase Convert

The syntax to convert lowercase and uppercase is as follows:

=~ tr / A-Z / a-z /;      # convert to lowercase

=~ tr / a-z / A-Z /;          # convert to uppercase

Example 7.6

$str1 = 'Shell Scripting in 8 Hours';

$str1 =~ tr/A-Z/a-z/ ;

print "$str1\n";

$str2 = 'Shell Scripting in 8 Hours';

$str2 =~ tr/a-z/A-Z/ ;

print "$str2\n";

Output:

shell scripting in 8 hours

SHELL SCRIPTING IN 8 HOURS

Explanation:

“$str1=~ tr/A-Z/a-z/;” converts the str1 to lowercase.

“$str2=~ tr/A-Z/a-z/;” converts the str2 to uppercase.

Remove Double Character

The words with double characters are like these: good, leek, see, woo, vacuum,  ……

The syntax to remove one of the double characters is:

=~ tr /a-z / a-z /s;

“/s” converts the double characters to a single character.

Example 7.7

$str = 'I see a bee over the book';

$str =~ tr/a-z/a-z/s;      # remove a double character

print "$str\n";

Output:

I se a be over the bok

Explanation:

“=~ tr/a-z/a-z/s;” removes one of the double characters. Therefore, the “see” becomes “se”, the “bee” becomes “be”, the “book” becomes “bok”.

Delete Specified Characters

The syntax to delete the specified characters is:

=~ tr  /character / /d;

“/d” deletes the specified characters.

Example 7.8

$str = 'HTML CSS in 8 Hours';

$str =~ tr/CSS/ /d;       # delete CSS

print "$str\n";

Output:

HTML in 8 Hours

Explanation:

“=~ tr/CSS/ /d;” deletes the specified characters “CSS” in the string.

Default Variable

When no any variable is defined explicitly, $_ is a default variable which contains all input values.

Therefore, $_ is a special default variable in Perl.

Example 7.9

foreach ('JAVE','HTML','PERL') {

print $_ ;       # $_ represents all element values

print "  ";

}

Output:

JAVE  HTML  PERL

Explanation:

In the above program, no any variable is defined explicitly, $_ is a default variable that contains all values “JAVA, HTML, PERL”.

Show the Perl comments

“__DATA__” is a parameter to make the comments to be shown.

The syntax to show the Perl comments is as follows:

while(<DATA>){ print $_; }

__DATA__

Example 7.10

while(<DATA>){

print $_;

}

__DATA__       # make the following comments shown

=pod

=head1

This is a pod document, which is used as a Perl comment.

=head2

Perl usually ignores the comment, but now I will be shown.

=cut

# I am a Perl comment

# This comment will  be shown by __DATA__

Output:

=pod

=head1

This is a pod document, which is used as a Perl comment .

=head2

Perl usually ignores the comment, but now I will be shown .

=cut

# I am a Perl comment

# This comment will  be shown by __DATA__

Explanation:

“__DATA__” is a parameter to make the comments to be shown.

The following is a pod document, which work as a comment.

The structure of a pod document is as follows:

=pod

=head1

…....

=head2

……

=head3

……

=cut

Hour 8

Class/Object

Class & Object

Class

Class is the general name for all things related, is a template of an object.

In Perl, a class is just a simple package, we can use a package as a class. The syntax to create a class is as follows:

package MyClass;

Object

Object is an instance of a class. We can create an object of a class. The syntax to create an object is as follows:

new MyClass( parameters);

Constructor

Constructor is used to initialize the properties of the class.

The syntax to create a constructor is as follows:

sub new {……}

Constructor

When creating an object, we need a constructor to initialize.

In Perl the structure of the constructor is a little complicated, so we need to study it in detail.

The structure of the constructor is as follows:

sub new {

my $class = shift;     # “shift” accepts all come-in parameters

my $self = { key => shift };     # { key => shift } is a hash

bless $self, $class;     # “bless” relates two parameters

return $self;     # “self” represents the instance of the class .

}

Explanation:

“sub new{…}” create a constructor.

“$class = shift;” accepts all come-in parameters when creating an object.

“shift” is a keyword which is used to process multi parameters.

{ key => shift } is a hash which assigns a value to a key.

“bless” is a keyword which is used to relate two parameters.

“return $self” returns a reference to the object.

Class & Object Example

Example 8.1

package Student;      # create a class

sub new {      # create a constructor

my $class = shift;

my $self = {

username => shift,

surname => shift,

number => shift,

};

print "Username: $self - > {username}\n";

print "Surname: $self - > {surname}\n";

print "Number: $self - > {number}\n";

bless $self, $class;

return $self;

}

new Student(" Ann", " Rose", " 1688") ;   # create an object

Output:

Username: Ann

Surname: Rose

Number: 1688

Explanation:

“package Student;” creates a class.

“sub new{……}” creates a constructor.

“shift” is a keyword which is used to process multi parameters.

“$self” keyword represents the instance of the class.

“bless $self, $class;” relates two parameters “$self” & “$class”.

“return $self;” returns the reference to object.

“new Student(" Ann", " Rose", " 1688");” creates an object and passes three parameters to the constructor.

Define a Method

The syntax to define a method is as follows:

sub myMethod {

my ( $self, $variable) = @_;

return $self - > {$variable};

}

Note: The first parameter should be a “$self” in Perl method.

“@_” accepts all come-in parameters

“return $self - > {$variable};” returns the value to the caller.

Example 8.2

package Student;     # create a class

sub new{      # create a constructor

my $class = shift;

my $self = {

username => shift,

surname => shift,

number => shift,

};

print "Username: $self - > {username}\n";

print "Surname: $self - > {surname}\n";

print "Number: $self - > {number}\n";

bless $self, $class;

return $self;

}

sub getUserName {        # define a method

my ( $self, $username ) = @_;  # @_ accepts parameters

return $self - > {username};    # returns value to the caller

}

1;     # The “1” indicates that the file is loaded successfully

$object = new Student(" Ann", " Rose", " 1688");

# create an object

$username = $object - > getUserName();    # call the method

print "The student username is     : $username\n";

Output:

Username: Ann

Surname: Rose

Number: 1688

The student username is : Ann

Explanation:

“sub getUserName {……}” defines a method “getUserName”

“@_” accepts all come-in parameters.

“return $self - > {username};” returns the value to the caller

“$object = new Student(……");” creates an object.

“$object - > getUserName();” calls the method “getUserName”.

Inheritance

A child class can inherit the feature of the parent class.

The syntax of the inheritance is as follows:

package ChildClass;     # create a child class

our @ISA = ParentClass;        # inherit a parent class

Example 8.3

package Student;     # create a class

sub new{      # create a constructor

my $class = shift;

my $self = {

username => shift,

surname => shift,

number => shift,

};

print "Username: $self - > {username}\n";

print "Surname: $self - > {surname}\n";

print "Number: $self - > {number}\n";

bless $self, $class;

return $self;

}

# define a method

sub getUserName {

my ( $self, $username ) = @_;

return $self - > {username};

}

1;

$object = new Student(" Ann", " Rose", " 1688");

# create an object

$username = $object - > getUserName();    # call the method

print "The student username is : $username\n";

package Pupil;      # create a child class “Pupil”

our @ISA = Student;      # inherit the parent class “Student”

$object = new Pupil( " Tom", " Watt", " 1689");

$username = $object - > getUserName();

print "The pupil username is     : $username\n";

Output:

Username : Ann

Surname : Rose

Number : 1688

The student username is :   Ann

Username : Tom

Surname : Watt

Number : 1689

The pupil username is :   Tom

Explanation:

“package Pupil;” creates a child class “Pupil”

“our @ISA = Student;” inherits a the parent class “Student”.

Package

A package is equal to a class. The default package name is “main” package, but we can create a new package.

package  myPack;        # create a new package

__PACKAGE__             # get the name of the package

Example 8.4

# in the default package

print "The Package Name : " , __PACKAGE__ , "\n";

package ipack ;      # create a new package “ipack”

print "The Package Name : " , __PACKAGE__ , "\n";

package main ;      # return the main package

print "The Package Name : " , __PACKAGE__ , "\n";

1;

Output:

The Package Name : main

The Package Name : ipack

The Package Name : main

Explanation: __PACKAGE__ gets the name of the package

BEGIN & END Modules

BEGIN{…}      # execute before any other statements

END{…}              # execute after any other statements .

Example 8.5

package myPack;

print "Note the sequence of statement running\n";

BEGIN {

print "Run the GEGIN module first. \n"

}

END {

print "Run the END module last. \n"

}

1;

Output:

Run the GEGIN module first.

Note the sequence of statement running

Run the END module last.

Explanation:

“BEGIN{…}”  is the first statement to run.

“END{…}” is the last statement to run.

Module

A Perl module is a reusable package, the module name is the same as the package name.

The syntax to create a module is as follows:

package MyModule;

The module will be referenced by another file.

The extension name of the module is “. pm”

Example 8.6

package MyModule;       # create a module

sub func{

print "I am MyModule. pm\n";

print "I am called by main. pl\n";

}

1;

Please save the module as “MyModule. pm” at C: \myPerl.

“package MyModule;” creates a module “MyModule. pm”;

This module will be referenced by another Perl file.

Require

“require” command is used to import a module. Its syntax is:

require  “ path/module    . pm ”;     # import a module

module     :: function();      # call the module’s function

Example 8.7

require "C:/myPerl/MyModule.pm";     # import the module

MyModule::func();      # call the function in the module

print "I am main. pl\n";

print "I am calling func in MyModule";

Please save the file as “main. pl” at C: \myPerl, and run it.

Output:

I am MyModule . pm

I am called by main . pl

I am main . pl

I am calling func in MyModule

Explanation:

‘require "C: /myPerl/MyModule. pm";’ imports a module.

‘MyModule:: func();’ calls func() in MyModule. pm.

Appendix

Perl Q & A

Questions :

Please fill in the correct answers.

01.

print "Hello! ";    # single-line comment

= fill in

multi-line comment

multi-line comment

multi-line comment

=cut

A. block     B. comment      C. module     D. pod

02.

fill in constant MON => "Monday";     # define a constant

fill in constant SUN => "Sunday";

print MON . "\n";

print SUN . "\n";

A. public      B. private      C. use      D. dim

03.

fill in score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');

print "$score{'60'}\n";

print "$score{'85'}\n";

print "$score{'100'}\n";

A. $       B. %       C. @       C. &

04.

fill in (boolean_expression){

# execute when boolean_expression returns false

}

A. except      B. if not     C. unless      D. if

05.

localtime()       # returns a local time

fill in ()       # returns a Greenwich time

time()     # returns the seconds accumulated since 1/1/1970

A. Greenwich     B. GreenwichTime     C. gntime     D. gmtime

06.

“open(DATA, ‘ +>> ’,  ‘myfile. txt’) or die $! ;” means

A. open the “myfile. txt” in append mode.

B. open the “myfile. txt” in read-only mode.

C. open the “myfile. txt” in write-only mode.

D. open the “myfile. txt” in read & write mode.

07.

die “ error message ”, fill in ;

# show error message from Perl

A. $_       B. $!        C. $$       D. $*

08.

fill in MyClass;

# create a class

A. class      B. new      C. create      D. package

09.

fill in "Here";     # define a Here Document

……

Here

A. <=        B. =>        C. <<        D. >>

10.

Which following statement can create an array?

A.    &arrayName = [val1, val2, val3];

B.    @arrayName = [val1, val2, val3];

C.    &arrayName = (val1, val2, val3);

D.    @arrayName = (val1, val2, val3);

11.

Which following statement can create a hash?

A.   &hash = ('key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3',...);

B.   %hash = ('key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3',...);

C.   &hash = ['key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3',...];

D.   %hash = ['key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3',...];

12.

fill in (condition){

code;

}

# The loop is executed when the condition is false, and exits the loop when the condition is true .

A. until      B. switch      C. while      D. do

13.

sub subName{

code fill in ;    # accepts all come-in parameters

}

A. &_      B. $_      C. %_      D. @_

14.

my $f = 'C: \myPerl\myfile. txt';     # the path & file to read

open(DATA, '<', $f) or die $! ;

while(<DATA>){

print fill in ;      # read all contents from myfile . txt

}

print "\nRead a file successfully! ";

close(DATA);     # close the file

A. &_      B. $_      C. %_      D. @_

15.

“sysopen(DATA, "myfile. txt", O_EXCL);” means

A. open a file “myfile. txt”, for read only.

B. open a file “myfile. txt”, for writing only.

C. open a file “myfile. txt”, for append only.

D. open a file “myfile. txt”, check whether the file exists.

16.

The syntax of the inheritance is as follows:

package ChildClass;     # create a child class

our fill in = ParentClass;    # inherit a parent class

A. @ASI      B. @IAS      C. @ISA      D. @SIA

17.

$score = 100;       # $score is a variable

print " $score \n" ;    # using double quotes

print '$score \n';    # using single quotes

What is the outup?

A.   100

B.   0

C.   nothing

D. $score \n

18.

$myStr = "Hello My Friends";     # create a string

@arr = split (' ', $myStr);     # convert to array

$str = fill in ( '**', @arr );     # convert to string

print "$arr[0] $arr[1] $arr[2] \n";

print "$str\n";

A. convert       B. join      C. string      D. str

19.

%score = ('60'=>'passed', '85'=>'ok', '100'=>'excellent');

@arr = fill in %score;   # get all element values of the hash

print "$arr[0]\n";

print "$arr[1]\n";

print "$arr[2]\n";

A. values       B. elements       C. hash       D. %

20.

$num = 10;

while( $num < 18 ){

if( $num == 15){  fill in ; }     # exit the loop block, end the loop

$num++;

print "$num  ";

}

A. first        B. exit        C. break        D. last

21.

$var = "Public String" ;     # define a public variable

sub show{

fill in $var = "Private String" ;     # define a private variable

print "$var\n";     # print private variable

}

print "$var\n";      # print public variable

show();

A. private       B. priv      C. my      D. state

22.

my $file = 'C: \myPerl\ourfile. txt';

fill in ( $file ) ;     # remove the file

print "Remove a file successfully! ";

A. remove      B. delete      C. eradicate      D. unlink

23.

while(<DATA>){

print $_;

}

fill in       # make the following comments shown

=pod

=head1

This is a pod document, which is used as a Perl comment.

=head2

Perl usually ignores the comment, but now I will be shown.

=cut

# I am a Perl comment

# This comment will  be shown

A. __PACKAGE__

B. __DATA__

C. __FILE__

D. __COMMENT__

24.

fill in "C:/myPerl/MyModule.pm";     # import the module

MyModule::func();      # call the function in the module

print "I am main. pl\n";

print "I am calling func in MyModule";

A. import      B. include      C. reference      D. require

Perl source code download link:

https://forms.aweber.com/form/04/1810519104.htm

Answers :

01    . D

09    . C

17    . D

02    . C.

10    . D

18    . B

03    . B

11    . B

19    . A

04    . C

12    . A

20    . D

05    . D

13    . D

21    . C

06    . A

14    . B

22    . D

07    . B

15    . D

23    . B

08    . D

16    . C

24    . D

Source Code Download

Perl Source Code Download Link:

https://forms.aweber.com/form/04/1810519104.htm

Source Code

Download

PowerShell Source Code Download Link:

https://forms . aweber . com/form/97/1907095997 . htm

Node.js Source code download link:

https : //forms . aweber . com/form/12/162246712 . htm

Django Source code download link:

https : //forms . aweber . com/form/31/448508031 . htm

Scala Source Code Download Link:

https : //forms . aweber . com/form/76/1081568876 . htm

Swift Source code download link:

https : //forms . aweber . com/form/22/1538006522 . htm

Perl source code download link:

https://forms.aweber.com/form/04/1810519104.htm

Table of Contents

PowerShell

Hour 1 Introduction

Hour 1 Introduction

Hour 2 Basics

Hour 2 Basics

Hour 3 Operators

Hour 3 Operators

Hour 4 Statement

Hour 4 Statement

Hour 5 Function

Hour 5 Function

Hour 6 String

Hour 6 String

Hour 7 Object

Hour 7 Object

Hour 8 Pipeline

Hour 8 Pipeline

Appendix 1

Appendix 2

Source Code Download

Node.Js

Hour 1 Introduction

Hour 1 Introduction

Hour 2 Basics

Hour 2 Basics

Hour 3 Event

Hour 3 Event

Hour 4 Write/Read

Hour 4 Write/Read

Hour 5 Stream

Hour 5 Stream

Hour 6 File

Hour 6 File

Hour 7 Operations

Hour 7 Operations

Hour 8 Modules

Hour 8 Modules

Appendix

Source Code Download

Django

Hour 1 Introduction

Hour 1 Introduction

Hour 2 Basics

Hour 2 Basics

Hour 3 Django Tags

Hour 3 Django Tags

Hour 4 Models

Hour 4 Models

Hour 5 Form/Method

Hour 5 Form/Method

Hour 6 Administration Tool

Hour 6 Administration Tool

Appendix 1

Python Basic

Appendix 2

Texts & Answers

Source Code Download

Scala

Hour 1 Introduction

Hour 1 Introduction

Hour 2 Basics

Hour 2 Basics

Hour 3 Operators

Hour 3 Operators

Hour 4 Statement

Hour 4 Statement

Hour 5 Methods

Hour 5 Methods

Hour 6 Arrays

Hour 6 Arrays

Hour 7 Collection

Hour 7 Collection

Hour 8 Class/Object

Hour 8 Class/Object

Appendix 1

Appendix 2

Source Code Download

Swift

Hour 1 Introduction

Hour 1 Introduction

Hour 2 Basics

Hour 2 Basics

Hour 3 Operators

Hour 3 Operators

Hour 4 Statements

Hour 4 Statements

Hour 5 String/Array

Hour 5 String/Array

Hour 6 Collection

Hour 6 Collection

Hour 7 Class/Object

Hour 7 Class/Object

Hour 8 Operations

Hour 8 Operations

Q & A

Source Code Download

Perl

Hour 1 Introduction

Hour 1 Introduction

Hour 2 Basics

Hour 2 Basics

Hour 3 Hash

Hour 3 Hash

Hour 4 Statement

Hour 4 Statement

Hour 5 Operations

Hour 5 Operations

Hour 6 Files

Hour 6 Files

Hour 7 Functions

Hour 7 Functions

Hour 8 Class/Object

Hour 8 Class/Object

Appendix

Perl Q & A

Source Code Download

Source Code Download