Wednesday, 28 March 2018

RESTful Web Services Tutorial 7 - Working With Databases (Insert Country using DBContext)

Hello! Good to see you, I really appreciate your effort in learning. Thumbs up to you!πŸ˜ƒπŸ˜ƒπŸ˜ƒπŸ˜ƒ

In this tutorial, we are going to acces the database we created in Tutorial 6 and Tutorial 7 with the help of Entity Framework. Entity Framework(EF) allows us to sync our  .Net application with the database and make changes from the .Net code.


We would cover the following in this tutorial
  1. Review of Tutorial 5 and Tutorial 6
  2. Examine the Changes to the Application Structure
  3. Modify the Controller File
  4. Write a Post Method for Country
  5. Insert some Countries Using the POST Method
  6. PUT Method
  7. DELETE Method
  8. Test all the Operations
  9. Next Steps

1. Review of Tutorial 5 and Tutorial 6


In Tutorial 5, we  installed SQL Server and then used SQL Server Management Studio to create the Employees sample database we would use to store the employees data. We also created the relationships between the tables using database diagrams.

In Tutorial 6, we went back to Visual Studio and created the Entity Data Model using Entity Framework. This makes is possible to automatically sync our .Net code with out database without having to write any stored procedure or any SQL queries.




2. Examine the Changes to the Application Structure


You need to understand what changes took place when you created the Entity Data Model

In the Solution Explorer, find EmployeeDataModel.edmx
(The edmx file is a container for both the designer/class diagrams and the models, the .cs files that hold the classes)
Expand this file to display the content. The folder structure is as shown in Figure 1

Figure 1: EntityDataModel.edmx


Notice that the Models have been created automatically for
  • Employee
  • Country
  • Address
  • Department
In Tutorial 3, we created the model file (Employee.cs) manually inside the Models folder, but in this case, the model files have been generated automatically from an existing database. This is known as Entity Framework - Database First.


3. Create the Controllers


Expand the Controller folder. Notice that we have already one controller file, the EmployeesController
You now need to create the controllers for Country
Right-click on the Controllers folder and Choose Add > Controller
Choose Web 2 API Controller Empty and shown in Figure 2

Figure 2: Web 2 API Controller Empty

Give it a name CountryController
Click Add. So the CountryController is added



4. Write a POST Method for Country


We would write a POST method that would insert a record into the database using the data from the body of the HTTP POST request.
Open the Country Controller file you created
Copy and paste the code in Listing 7.1 inside the class


        //METHOD TO ADD A NEW COUNTRY
        [HttpPost]
        public IHttpActionResult AddCountry([FromBody]Country country)
        {
            using (var db = new EmployeeDBEntities())
            {
                db.Countries.Add(new Country() 
                {
                    Id = country.Id,
                    Name = country.Name,
                    Capital = country.Capital,
                    Code = country.Code,
                    Nationality = country.Nationality
                }
                );
                db.SaveChanges();
            }
            return Created(Request.RequestUri, Request.Content);
        }
Listing 7.1: POST Method for Country

The code is quite simple. The EmployeeDBEntities is known as a database context and provides functionality to handle database operations like Add(), Remove(), Delete() and SaveChanges().

In this case, we got a Country object from the body of the request. Then extracted the fields  and used them to create a new Country which is given to the Add() method as parameter. The Add method runs some kind of insert query against the database.
The SaveChanges() commits the query.

Before we test this code, write a code to retreive a list of countries. This is given in Listing 7.2.
Copy and paste this code into the CountryController.



        [HttpGet]
        public IEnumerable<Country> getCountries()
        {
            var db = new EmployeeDBEntities();
            return db.Countries;
        }
Listing 7.2: Code to Get List of Countries

So now you have the POST method to Add a new Country as well as a GET method to retrieve the list of countries
Build the project and make sure it builds successfully.


5. Insert some Countries Using the POST Method


Run the program.
Open Advanced REST Client
Make a POST request using the code in Listing 7.3 as the request body. You can see how to make POST request with ARC in Tutorial 4.

POST Request url: http://localhost:24675/api/Country/getCountries


}
"Id": 1,
"Code": "NGN",
"Name": "Nigeria",
"Capital": "Abuja",
"Nationality": "Nigerian"
}
Listing 7.3: POST Request Body

Change the data to insert two more Country records
Make a GET request to retrive a list of countries

GET Request url: http://localhost:24675/api/Country/AddCountry




6. PUT Method to Update a Record



Listing 7.4 gives the PUT method to edit and update a country from the database.
Copy and paste this code in the CountryController file.
I have used lambda expression to select a country whose id corresponds to the id coming from the request body.

The where clause in the lambda expression reads:

"where s such that s.Id is equal to country.id"

        //METHOD TO UPDATE A COUNTRY
        [HttpPut]
        public IHttpActionResult EditCountry([FromBody]Country country)
        {
            using (var db = new EmployeeDBEntities())
            {
                var oldCountry = db.Countries
                    .Where(s => s.Id == country.Id)
                    .FirstOrDefault();

                    oldCountry.Name = country.Name;
                    oldCountry.Capital = country.Capital;
                    oldCountry.Code = country.Code;
                    oldCountry.Nationality = country.Nationality;

                   db.SaveChanges();
            }
            return Ok();
        }
Listing 7.4: PUT Method to Update a Country



7. DELETE Method to Delete a Record


The DELETE method is given in Listing 7.5 to delete a record from the database.
Copy and paste this code in the CountryController file

Notice the four lines needed to delete a record
  • the Attach method attached the  entity (coming from the request) to the database context
  • the Remove method carries out the delete operation
  • the next line updates the context
  • the SaveChanges commits the delete operation

        //METHOD TO DELETE A COUNTRY
        [HttpDelete]
        public IHttpActionResult DeleteCountry([FromBody]Country country)
        {
            using (var db = new EmployeeDBEntities())
            {
                db.Countries.Attach(country);
                db.Countries.Remove(country);
                db.Entry(country).State = EntityState.Deleted;
                db.SaveChanges();
            }
            return Ok();
        }
Listing 7.5: DELETE Method to Delete a Country




8. Test all the CRUD Operations


At this point, you can carry out INSERT, SELECT, UPDATE and DELETE operation on the Countries database using the CountryController.
Run the program
Using Advanced REST Client, insert some records  into the database. Remember to change the Id for each new insert because the insert would fail if the Id is not unique
Perform some PUT and DELETE requests to make sure it works well

If everything works fine, then congratulations! If you have some challenges, let me know in the comment box below.

9. Next Steps


We have successfully completed the REST API for manipulation the Countries information. Now, as a quiz, try to create controllers for the other three tables:
  • Employees
  • Departments
  • Addresses
If you did it correctly, fine. In the next lesson, Tutorial 8, I would give you the code for the other tables without giving much explanation. For now, try to do it yourself.

I would like to thank you for learning!!

πŸ‘†πŸ‘†πŸ‘†TopπŸ‘†πŸ‘†πŸ‘†





Tuesday, 27 March 2018

Hypothesis Testing Question 21 - Walf-Wolfowitz Run Test for Large Sample (Step by Step Procedure)

Question 21
The following arrangement of men, M, and women, W, lined up to purchase tickets for a rock concert:



Test for randomness at the Ξ± = 0.05 significance level

Solution Steps
In this case, we see that the sample size is fairly large, so we are going to use a slightly different method in this case. We are going to calculate the mean runs and the standard deviation.

Then we go ahead to find the z-statistic. We would use the following 7 steps to disolve this problem.

Step 1: State the null and alternate hypothesis
Step 2: Determine the number of runs
Step 3: Calculate the mean runs
Step 4: Calculate the Standard deviation
Step 5: Calculate the z-Statistic
Step 6: Determine the Critical value
Step 7: Draw a conclusion


Step 1: State the null and alternate hypothesis


H0: Arrangement is random
H1: Arrangment is not random

Step 2: Determine the Number of Runs


This means that you need to mark each of the categories so you can easily count them
Here I mark each run alternatively with red for M and black wor W. The outcome is given below.


The number of runs is given by R = 27
The number of Men, n1 = 30
The number of Women, n2 = 18



Step 3: Calculate the Mean runs


The mean is given by the formula


We can go ahead to substitute the value of n1 = 30 and n2 = 18


Step 4: Calculate the Standard Deviation


You can  find the standard deviation for a runs test using the formula


We can go ahead to substitute the value of n1 = 30 and n2 = 18



Step 5: Calculate the z-Statistic


The z-Statistic can be calculated using the formular



Then we can substitute the value of
R = 27
ΞΌR = 23.5
ΟƒR = 3.2083



Step 6: Determine the Critical Value


Look up the value of the critical value from statistical table of normal distribution
We get a critical value for of 1.96

Step 7: State the Decision


Since the calculated value of z = 1.0909 is within the accept region(less than the critical value of 1.96), we therefore accept (fail to reject) the null hypothesis and conclude that there is not real evidence that the arrangement is not random


Leave a comment if you have any observation or difficulty following this lesson
Thank you for solving.

Hypothesis Testing Question 20 - Run Test( Suppose we flib a coin...)

Question 20
Suppose we flip a coin n = 15 times and come up with the following arrangements

H T T T H H T T T T H H T H H

(H = head, T = tail)

Test at the alpha = 0.05 significance level whether this arrangement may be regarded as random.

Solution Steps
Stetp 1: State the null and alternate hypothesis
H0: Arrangement is random
H1: Arrangement is not random

Step 2: Calculate the Test Statistic (Number of Runs)
Normally you separate each of the runs so that you would be able to count them.

TTT  HH  TTTT  HH  HH

Number of runs is given by r = 7
Number of H, n1 = 7
Number of T, n2 =8

Test Statistic = 7 (number of runs


Step 3: Lookup Critical values in table of runs tests
At  \varepsilon \!  = 0.05 signnificance, n1 = 7, n2 =8
Upper critical value =  4
Lower critical value = 13

Step 4: Make Your Decision
Since r = 10 which is between 4 and 13, we accept the null hypothesis (we fail to reject it)

Step 5: Draw a Conclusion
There are not enough evidence to reject the claim hat the pattern of occurence of heads and tails is determined by a random process




Classification in Machine Learning

In this lesson, we are going to examine classification in machine learning.  Below are the topics we are going to cover in this lesson
  1. Formulation of the Problem
  2. The Cancer Diagnosis Example
  3. The Inference and Decision Problems
  4. The Role of Probability
  5. Minimizing Rate of Misclassification
  6. Minimizing Expected Loss
  7. Approaches to Classification bases on a Priori Knowledge
So let's begin with the first one

1. Formulation of the Problem

Suppose we have an input vector x together with a corresponding vector t of the target variable. This set of input vector x, and target vector t forms the training data set.
Now, the goal is to predict t for a new value of x. For classification problem, t would represent class labels. The joint probability distribution p(x, t) provides a complete summary of the uncertainty associated with these variables. Determination of this probability from the training data set is an example of inference problem

2. The Cancer Diagnosis Example

Let's take the example of the medical diagnosis problem where we need to determine whether or not the patient have cancer. An x-ray image of the patient is taken, so the input vector x is a set of pixel intensities of the x-ray image. The output variable t will represent the presence or absence of cancer. Now we can form two classes C1 and C2. C1 represents the presence of cancer while C2 represents the absence of cancer.
We need to assign the input to one of the two classes.

3. The Inference and Decision Problems

The general inference  involves determining the joint distribution p(x, Ck), or p(x,t), which give the most complete probabilistic description of the problem. This is the inference step.
After this, a decision is made whether to give treatment or not. This is the decision step. This step becomes easy if the inference problem have been solved.

4. The Role of Probability

When the x-ray images is obtained x for a new patient, the goal is to determine which of the two classes to assign the image.
We could assign it to any of the two classes, C1 or C2 (let's use Ck, for k = {1,2}). We need to find the probabilities of the two classes given the image. This probability is given by p(Ck | x). Using Bayes theorem, these probabilities can be expressed in the form:



5. Minimizing Misclassification

Sometimes in classification, we may assign an input to the wrong class. In this case, misclassification have occurred. The goal is to make as few misclassifications as possible.
Misclassification occurs when an input variable is assigned to the wrong class. The goal is to minimize the number of misclassifications.
We handle this by creating a rule that assigns each x to one of the available classes. This rule would divide the input space into regions Rx called decision regions, one region for each class.
Points in Rx are assigned to Ck.
A misclassification when a point in a region is assigned to the wrong class e.g
  • x is in R1 but is assigned to class C2
  • x is in R2 but is assigned to class C1

The probability of misclassification is given by


To minimize this error, the rule must assign x to which class has minimum integrand
p(x, Ck) = p(Ck | x)p(x)
From the above formula, to minimize misclassification, x should be assigned to which class the posterior probability is largest.

6. Reducing Expected Loss

The case of cancer dignosis shows that a loss incurred when there is misclassification could be of different degrees.
So we introduce a loss function or cost function E(L).
Suppose that for a new value of x, the correct class is Ck but we assign it to Cj (where j  k). In this case, we have incurred some loss Lkj.
where k and j are elements of the loss matrix, (as in the case of cancer diagnosis). 
The optimal solution is the one that minimizes the value of the loss function. 
The average loss depends on the joint probability p(x, Ck) and is given by


The objective  is to choose Rj in order to minimize the expected loss. If we know the posterior probability p(Ck, x), then we can minimize the loss.


7. Three Approaches to Classification


The three approaches to classification are
Determination of the class conditional probabilities
Determination of the posterior probability directly
Use a Discriminant function

a. Determine the Class Conditional Probabilities
Determine the Class Conditional Probabilities p(x|Ck) for each class. Then determine the prior probabilities p(Ck) for each class. Then using Bayes theorem,  determine the posterior probability.

b. Directly Determine the Posterior Probabilities
Solve the inference problem by first obtaining the posterior class probabilities p(Ck |x) for each class. Then use decision theory to assign new values of x to classes.

c. Use a Discriminant Function
Find a function f(x) called a discriminant function that would map each input directly to a class label. For example:



Hypothesis Testing Question 19 - Run Test ( Trees were planted...)

Question 19
Trees planted along the road were checked for which ones are healthy(H) or deseased (D) and the following arrangement of the trees were obtained:

H H H H D D D H H H H H H H D D H H D D D

Test at the  \varepsilon \!  = 0.05 signnificance wether this arrangeemnt may be regarded as random


Solution Steps
Stetp 1: State the null and alternate hypothesis
H0: Arrangement is random
H1: Arrangement is not random

Step 2: Calculate the number of runs, H and D

H H H H D D D H H H H H H H D D H H D D D D

Number of runs is given by R = 6
Number of H, n1 = 13
Number of D, n2 = 9


Step 3: Lookup Critical values in table of runs tests
At  \varepsilon \!  = 0.05 signnificance, n1 = 13, n2 = 9

Step 4: State your Conclusion
In this case , since the absolute value calculated is less than the critical value, we reject the null hypothesis and conclude that the arrangement is not random

Note about the Run Test
The Run Test (which is also the Wald-Wolfowitz runs test) is a non-parametric statistical test that tests the randomness of a hypothesis for a 2-valued sequence of data.
It is used to test the hypothesis that the elements of the sequence are mutually independent


Bot Framework Tutorial 5: How to Train a Question and Answer(QnA) Bot

This tutorial follows from the Tutorial 4 where we create a Question and Answer Bot. In this tutorial, we would focus on improving the functionality  of our the question and answer bot so that it can give more intelligent answers to questions.


Today we would focus on Create a chat robot that would answer any question about Computer Programming and we would do this together


  1. Examine the Base Questions
  2. Add Your own questions
  3. Create a QnaServer in qnamaker.ai
  4. Test the Service
  5. Train Your Service
  6. Quiz for You
  7. Publish and Test  The Service
  8. Create a New Question and Answer Bot in Azure
  9. Final Notes and Next Steps


1. Examine the Base Questions List


For this tutorial, we would start with a basic list of computer programming questions. You can view these questions from here.

Figure 1: Base Questions List


Figure 1 shows the base qustions list that would serve as our starting point


2. Add Your own questions


You can add more questions to this list. Just leave the question in the comment box under the list. You could also leave the question in the comment box under this tutorial.

If you have the answer to the question you could provide it along with the question, if not, then we would provide the answer and add it to the list in a short time.

Figure 2: Add Your Question here


If would like to have access to the Programming Questions and Answers page, then mention that in the comment box, as well as your email. After verifying that the request is authentic, then we would provide you with a link to edit the questions and answers list and add your own questions.


3. Create a QnaServer in qnamaker.ai


Step 1: Visit qnaMaker.ai
Step 2: Click on Create New Service
Step 3: Enter the name of the Service (eg. Programming-Questions-Service)

Now you need to enter the url of the knowledgebase. The knowledgebase is simply the list of question and answers we already have.


Figure 3: Create new Qna Service


Step 4: Enter the url of our programming questions and answers page: http://kindsonthegenius.blogspot.hu/2018/03/computer-programming-questions-and.html
Copy and paste the url in the box

Step 5: Scroll down the page and click on the create button
After some seconds, the knowledgebase is created as shown in Figure 4.

Notice that the  system recognizes which text is a questions and which is the answer to the question. Also, any image is the file or text that is not question and answers are ignored.
Isn't this amazing!


4. Test Your Service


To test our service:
Step 1: Click on the Test menu by the left
The testing page is displayed as shown in Figure 4

Figure 4: Testing Page

Step 2: Enter some of the questions we have in the list and observe the response.
You would observe that it gives the correct response.
Let's now move to the training section so we see how we can improve performance


5. Train Your Service


However, you entered the questions exactly as it is because you already have the list of question. But a user trying to ask questions about computer programming may ask questions in a different way or with different wordings.

For example, the three questions should produce the same answer(at least for a simple bot):

  • Can you tell me about JVM?
  • What is Java Virtual Machine?
  • What does JVM stand for?


Step 1: Try to enter this three questions and what do you observe? Give answer in the comment box below.

Step 2: Now Enter What is Java Virtual Machine.
You will observe that it give us the wrong answer πŸ˜ƒ

Training would help us fix this.

Step 3: Now enter What is JVM, so that is gives the right answer.
We want it to give us the same answer when we enter What is Java Virtual Machine

Step 4: By the right hand side, in the text box under 'provide multiple alternative phrasing to the question to broaden the knowledge base', enter What is Java Virtual Machine
Step 5: Click Add (the + sign)
Notice that the question is added as a second question for this particular answer as shown in Figure 5

Figure 5: Training the Qna Service


Step 6: Click on Save and Retrain
Step 7: Now, Enter the question again, What is Java Virtual Machine

What do you observe?
Notice now that it gives the right answer

6. Quiz for you


Train the Service the give the same answer for the following quesionÉ

What are some Languages in Programming
Mention some programming languages
Give examples of programming languages

Also take some time to train the service to handle other variations of the other questions in the list. Remember to click on Save and Retrain when you are done with the training.



7. Publish and Test  The Service


After you are done with the training:
Step 1: Click on Publish. A review page is displayed
Step 2: Click on Publish again to publish the service

Figure 6: Publish Success page

Now, you can see Success page.
In this page you will find the KnowledgebaseId and the Subcription Key.
Step 3: Copy and save this output, because you will need it in the nex tutorial.

8. Create a New Question and Answer Bot in Azure


You will need to do this by yourself.
See How to Create a Question and Answer Bot
Give the bot a name like ProgrammingBot or ProgrammingAssistant or ProgrammingTutor

9. Final Notes and Next Steps


Now we have a working qna Service and we have a question and answer bot. This is interesting because in the next tutorial we would examine how allow users to use this bot for free.

You know, the public could make use of your bot and it would even apear that they are chatting with someone
In the next tutorial, we would examing Channels and also  add Skype channel to this bot so that it can connect with and chat with real users

For now I would like to thank you for the time spent learning. Do leave a question or observation if you have any.


Computer Programming Questions and Answers (Java, C, C++, PHP, Python, JavaScript, Visual Basic, C#, HTML)

To submit a question, the question (and answer) in the comment box belowπŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡

What is Computer Programming?
Computer Programming is the process of developing the instructions used by the computer toe perform tasks

What is Programming Language?
A programming language is a language used to specify the instructions to be followed by a computer to perform a specific function

Give Examples of Programming Languages?
Some examplese of programming languages are: Java, C++, C, C#, Visual Basic, Ruby, Perl, JavaScript and PHP

What is a High Level Language?
A high level language is a programming language written in a way similar to natural language used by humans to communicate

What is an Assembly Language?
An assembly language generated by a compiler as an intermediate language between a high level language and a low leve language.

What is a Compiler?
A compiler is a piece of software that is used to translate computer programs written in high level language to machine language

What is Machine Language?
Machine Language is the basic language used by the computer hardware. Machine language is normally in the binary (1s and 0s) form

What is a Loop in Programming?
A Loop in computer programming is a programming construct that executes a piece of code or a number of times based on some criteria

What is an Array?
An array is a data structure that is used to group a number of values together under the same name

What are some types of Loops?
Some types of loops are For Loop, Do-While Loop and While Loop

What is Queue?
A Queue is a data structure that allows for insertion and deletion of items such in a First-In-First-Out basis. The first item inserted is the first to be removed.  Items are inserted from one end called the head and items are removed from the other end called the tail.

What is Stack?
A Stack is a data structure that allows for insertion and deletion of items such in a Last-In-First-Out basis. The last item inserted is the first item to be removed.  Items are inserted and deleted from the same end of the stack. Removing item from the top of the stack is called popping.

What is SDLC?
SDLC stands for Software Development Life Cycle. It is a methodology that specifies  the various steps taken to develop a computer software.

What is an algorithm?
An algorithm is a sequence of steps taken to perform a particular task

What is JVM?
JVM Stands for Java Visual Machine and is a piece of software that installed in a computer to enable it run programs written in Java. JVM runs the Java Bytecodes



Monday, 26 March 2018

What is Run Test in Statistics - A Simple Explanation with Step by Step Examples

Good to see you again! Hope you are doing fine
πŸ˜€
The Run Test is actually one of the most interesting statistical test ever and it is so easy to understand, or even the easiest. Remember that if you have any difficulty following this lesson, let me know in the comment box below. πŸ‘‡πŸ‘‡πŸ‘‡ I would clearify
 

In this simple lesson, we are going to explain in very simple and clear terms, the concept of run test in statiscs

Content
  1. What is  Run Test?
  2. What is a Run?
  3. Example of Runs 
  4. Run Test Procedure
    • Hypothesis
    • Test Statistic and Decision Rule
    • Critical Value
  5. Example 1 and Solution
  6. Example 2 and Solution
  7. Example 3 and Solution
  8. Solving With Formular for large samples 
  9. Final Notes


1. What is Run Test


Run test is a statistical test used to determine of the data obtained from a sample is ramdom. That is why it is called Run Test for Randomness.
Randomness of the data is determined based on the number and nauture of runs present in the data of interest.

2. What is a Run?


A run is a sequence of similar or like events, items or symbols that is preceded by and followed by an event, item or symbol of a different type,  or by none at all.
Randomness of of the series  is unlikely when there appear to be either too many or two few runs. In this case, a run test need to be carried out to determine the randomness.
The Run Test when performed helps us to decide whether a sequence of events, items or symbol is the result of a random process.

3. Example of Runs


A data scientist carrying out a research interviewed 10 persons during a survey. We denote the genders of the poeple by M for men and W for women.
Assuming the respondents were chosen as follows:

Scenario 1
M M M M M F F F F F

Scenario 2
F M F M F M F M F M

Scenario 3
F F F M M F M M F F

Scenario 1 has only 2 runs and therefore the scenario cannot be considered random because there are to few runs

Scenario 2 has too many runs, 5 runs. And therefore would not be considered as random

Scenario 3 has 5 runs and therefore we need to perform a test to determine the randomness of the data.


4. Run Test Procedure


First we need to assume that the data available for the analysis consistes of a sequence of observations, recorded in order of occurence, which we can categorize into two mutually exclusive types.

First, you need to determine the total sample size, then the number of observation ofeach type as presented below:

n = total sample size
n1 = the number of observation of one type
n2 = the number of observations of the other type

Hypothesis
Then State the null and alternate hypothesis

A. TWO-SIDED
H0: the pattern of occurence is random
H1: the pattern of occurence is not random

B. ONE-SIDED
H0: the pattern of occurence is random
H1: the pattern of occurence is not random (because there are too few runs to be atributed as random)

C. ONE-SIDED
H0: the pattern of occurence is random
H1: the pattern of occurence is not random (because there are too few runs to be atributed as random)


Test Statistic and Decision Rule
The test statistic is r = total number of runs
The decision rules is also called the acceptance or rejection criteria. It depends on the test statistic(calculated) and the value and the values of upper and lower limits(from statistical tables)

Table 1: Decision Rule


Critical Value
Critical value is determined from statistical table using n1 and n2








We can solve some examples to clarify this.  



5. Example 1


On a commuter train, the conductor want to see whether the passengers entering a train enter in a random manner. He observes the first 25 people, with the following sequence of males(M) and females(F).

F F F M M F F F F M F M M M F F F F M M F F F M M

Test for randomness at Ξ± = 0.05

Solution Steps
Step 1: State the null and alternate hypothesis
H0: The patter of occurence of males and females enter the train is random
H1: The pattern of occurence of males and females entering the train is not random

Step 2: Find the test statistic (number of runs)
You can easily get this by grouping each run as shown below:

FFF  MM   FFFF   M   F   MMM   FFFF   MM   FFF   MM

Test statistic, r = 10
n1 = number of females = 15
n2 = number of males = 10

Step 3: Find the critical value
We can find the lower and upper critical value from statistical run table
n1 = 15, n2 = 10
Lower critical value = 7
Upper critical value = 18

Step 4: Make your decision
Since r = 10 which is between 7 and 18, we accept the null hypothesis (we fail to reject it)

Step 5: Draw a Conclusion
There are not enough evidence to reject the claim hat the pattern of occurence of males and femals enter the train is determined by a random process



6. Example 2


We have 20 people that enrolled in a drug abuse program. Test the claim that the ages of the people, according to the order in whihc they enroll occur at random, at Ξ± = 0.05.

The data are as follows:
18, 36, 19, 22, 25, 44, 23, 27, 27, 35, 19, 43, 37, 32, 28, 43, 46, 19, 20, 22

Solution Steps
Step 1: State the hypothesis and identify the claim

The claim is the null hypothesis H0 and the hypothesis is the alternate hypothesis H1.
H0: The pattern of occurence of ages of the people enrolled in a drug abuse program is determined by a random process
H1: The pattern of occurence ofa ages of people enrolled in a drug abuse program is not random

Step 2: Find the test statistic (number of runs)
To find the number of runs we first arrange the data  in ascending order and find the median of the data set.

Then compare the original data with the median. The replace the above median in the original sequence with an A if it is above the median and with B if it is below the median.(you can also use the mean instead of median)
I have done this using excel and the result is shown below:


We can now arrange the data according to runs and we would have the output below:
B  A  BBB   B  A  B  AAAAAA   BBB

From the above  we have

Test statistic, r = 9
n1 = number or A runs = 9
n2 = number of B runs =9


Step 3: Find the Critical Value
n1 = 9, n2 = 9
From statistical table of Runs Test, we get the critical values

Upper critical value = 5
Lower critical value =15

Step 4: Make the decision
Since the statistic r is between the upper and lower critical values, we accept H0


Step 5: Draw your conclusion
There is not enough evidence to reject the claim that the patter of occurence of ages of people in th program is determined by a random process



7. Example 3:


Table 1.0 shows the departures from normal of daily temperatures recorded at Atlanta, Georgia during February1969. We would like to know whether we may conclude that the pattern of departures above and below normal is the result of a non-random process.


Solution Steps

Step 1: State the null and the alternate hypothesis
H0: The pattern of occurence of negative and positive deviations from normal is determined by a random process
H1: The pattern of occurrences of negative and positive deviations from normal is not determined by a random process (claim)

Step 2: Find the test statistics (number of runs)
To get the number of runs, we need to find the departures from normal above and below zero. The departures from normal that is above 0 are recorded as A and those that are below 0 are recorded as B.
If we do this we would have the arrangement as follows:

AAAAAA B A B AA BBBBB AAAAAAAA BBBBBB

Test Statistic (number of runs) r = 8
n1 = number of A = 17
n2 = number of B = 13

Step 3: Find the critical value
n1 = 17, n2 = 13

Using statistical table  we find the:
Lower critcal value = 10
Upper critical value = 22

Step 4: Make the decision
Since r = 8, which is lower than the critical value, we reject the null hypothesis (H0)

Step 5: Draw the conclusion
There is enough evidence to support the claim that the pattern of occurence of positive and negative departures from normal is not random

8. Formular for Large Samples


What if the sample size is large? In this case we could use a formula to solve it. This formular calculates the the test statistic based on n1 and n2.
The formula is given by:


Then we can look up the critical value in the table of normal distribution

9. Final Notes


Now that you have completed the lessons on run tests. Thumbs up to you! One thing you can be sure is it does not get more complicated than this.
Just a a quiz, try to solve the three examples using the formula presented and compare the result you have with the result gotten without using the formula




RESTful Web Services Tutorial 4 - Testing the REST APIs using Advanced REST Client

Good to see you again! It is good to know that you have come this far. Thumbs up to you! πŸ‘πŸ‘πŸ‘πŸ‘


In this tutorial, we would cover the following topics
  1. Review of Tutorials 2 and 3
  2. About REST Clients
  3. Important Concepts of REST Client
  4. Test the POST Request
  5. Test the PUT Request
  6. Test the DELETE Request
  7. Next Steps - Using Data
If you have any difficulty following this tutorial, explain in the comment box below and I would give you the needed supportπŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡


1. Review of Tutorial 3


In Tutorial 3, we successfully creates all the methods for the CRUD operations (GET, POST, PUT and DELETE). Meanwhile CRUD means Create, Read, Update and Delete.
You could go to Tutorial 3 if you have not done so because this lesson follows from Tutorial 3. 


2. About REST Clients


A REST Client allows you to test RESTful APIs by providing a way of makings a request to the API and specifying neccessary criteria needed to conform to the RESTful architecture. These features provided by a REST client is not readily available in a normal browser application. Two important

REST Clients, which I use and are free are:
  • Postman REST Client
  • Advanced REST Client
In this tutorial, we would use Advanced REST Client(ARC)

3. Important Features of REST Clients


Remember that to do a GET request, we simply specify the Request URL and select the GET Method. But in this case, we need to do a POST request which requires specifying additional attributes.
These are:

1. The Request Body
This is the body of the request which contains the data to be used to create a new resource(in our case, a new Employee).
The Request Body shows up when you select POST as the method in the methods list. It apears as a tab between Headers and Variables.

2. Body Content Type
This specifies the type of format of the data you want to pass accross in the body of the request

3.Request-Header
The Header (or HTTP Request Header) allows the client to pass additional information along with the request to the API.


Figure 1: POST Request Body


4. Test the POST Request


To carry out this task, be sure that you have completed Tutorial 3. Follow the  steps below.
Step 1: Open the Employee application we created in Tutorial 3
Step 2: Run it by pressing F5
Step 3: Make sure  that the browser window opens up

Step 4: Lunch Advanced Rest Client (you can launch by entering this link in Chrome https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo because the Advanced REST Client is a Chrome extension)
Step 5: Select POST from the list of methods
Step 6: Enter this POST Request URL, which is :

http://localhost:24675/api/Employee/AddEmployee

Also make sure you use the correct port number which you can get from your browser

Step 7: Now enter the body of the request to create a new Employee. I have created it below, but you can change to any values you wish


 {
"EmployeeId": 5,
"Name": "Kindson",
"City": "Akokwa"
}
Listing 1: Request Body of POST Request

Step 8: Change the Body content type to application/json
Step 9: Click on the Header tab and Click on Insert headers Set. A default headers set is displayed
Step 10: Click on USE THIS SET under it. The screen is shown in Figure 2

Figure 2: Inserting Headers Set


At this point, you are now ready to send the POST request

Step 11: Click on the SEND button

If you have followed the steps correctly, you should have a response code:

201 Created

If you don't have this result, let me know by leaving a comment in the comment box below.


5. Test the PUT Request


The PUT request is used to edit an existing record. What normally do is to display the record I want to edit, then copy it and use it as the body of the PUT request.

The steps you will follow is similar to the steps for the POST request. I would only outline the few differences:

Step 1: Make a GET Request to the employee of Id = 1

http://localhost:24675/api/Employee/Employees/1

Step 2: Highlight an copy the record returned by the request
Step 3: Select PUT from the methods list instead of POST

For the PUT request, use the URL

http://localhost:24675/api/Employee/AddEmployee/1

assuming we want to edit the employee record with Id of 1

Step 4: Paste the request body without the Id
Step 5: Make the needed changes in the record in the request body.
Step 6: Click on SEND to complete the request

6. Test the DELETE Request


For the DELETE request, take note of the following points as it is very similar to the PUT request but without a request body.

Step 1: Select DELETE in the methods list

Don't specity anything in the Request Body (to delete the entire record)
Step 2: Enter the DELETE request URL is given by

http://localhost:24675/api/Employee/AddEmployee/2

in case you want to delete the employee record with Id of 2

Step 3: Click on SEND

Quiz: What response did you get for the DELETE request?
Leave your answer in the comment box below

Any problem: If you have any difficulty following this tutorial, explain in the comment box below and I would give you the needed support.

7. Next Steps - Using Data


You can observe that the changes we make throught the REST requests are not saved back to anywhere. This is because we have not implemented any functionality to store our data.
The current data we use are hard-coded into the the controller file. In the real production application, you would never have to do anything like this.
Therefore in the next tutorial, Tutorial 5, we would set up out application to work with MSSQL database.
Then in Tutorial 6, we would generate the equivalent class diagram in Visual Studio

For now I would like to thank you for the time you spend learning!



Sunday, 25 March 2018

RESTful Web Services Tutorial 6 - How to Create an Entity Framework Class Diagram in Visual Studio

Good to see you again!
Feel free to mention any issue you have to me using the comment box under this lesson.
In this tutorial, I will teach you how to generate your class diagram in Visual Studio. This is very interesting because I normally use Microsoft Visio or some other designer to manually draw class diagrams in the past. And the more interesting thing is that this diagram is in sync with your database design.





To generate the class diagram in Visual Studio, follow the steps below:
Step 1: Open Visual Studio
Step 2: Open the Solution we created in the previous tutorial. You can create a new Solution if you did not follow the previous tutorial.
Step 3: In the Solution Explorer, right-click on your project and select Add > New Item to open the New Item dialog.

Under Visual C#, select Data as shown in Figure 1

Figure 1: New EF Data Model


Step 4: In the list of items, select ADO.NET Entity Data Model
Step 5: Give it a name like EmployeeDataModel.
Step 6: Click Add to display the Entity Data Model wizard as shown in Figure 2

 Figure 2: Entity Data Model Wizard


Step 7: Make sure that 'EF Designer from database' is selected
Step 8: Click on Next. The next Wizard Step is displayed as shown in Figure 3

Figure 3: Choosing Database Connection




Define Database Connection Parameters
Now we need to connect to the database we created by specifying the name of the server, the instance and the name of the database.

Step 9: Click on New Connection to display the Connection Properties dialog

In the Connection Properties dialog box that appears, enter the Connection Properties as shown in Figure 4
Step 10: Enter the Server Name
Step 11: Select the name of the database you created under Select or enter database name


Figure 4: Database Connection Parameter


You could also Click on Test Connection to ensure that the connection succeeds.

Step 12: Click on Ok to get back to the Data Model Wizard. A dialog box appears prompting you to select an Entity Framework.

Figure 5: Connnection Settings (ConnectionString)


Figure 6: Choose Entity Framework Version


Step 13: Select Entity Framework 6.0. Other versions would also work

Step 14: Click on Next

Figure 7: Choose Database object(Tables)





Step 15: Select the checkbox for Tables (We discuss Views and Stored Procedures in subsequent lessons)
Step 16: Click Finish to complete the task

After a few seconds, the Class diagram is generated as you can see in Figure 8. Isn't this amazing!

Figure 8: Completed Class Diagram



Notes About This Class Diagram
Notice that there is a fifth object in the diagram with a name of sysdiagram. Delete it.
You can also see that this diagram resembles the relationship diagram we created in Tutorial 5, with the relationships labelled.

Each of the classes is has two sections
  • Properties: This corresponds to the fields of the particular table in the dabase
  • Navigation Properties: This is additional information that could be selected along with the given record. For instance, for an Employee, we need to select his address, country and department. Note that they have singular name. In other tables like Departments, the navigation properties specifies the Employees that belong to a particular department. Also note that the navigation property here is plural reflecting the one-to-many relationship(one department to many employees). This would become clearer as we progress

Final Notes
Now that we have completed developing the data tier of our REST API application, we are now ready to go back to continue working on the main REST API files.
In the next tutorial, we would use REST request to perform GET, PUT, POST and DELETE operations on the actual data on the database.

For now I would like to thank you for your efforts! You are doing great!
Remember to leave a comment if you have any challenge following this tutorial.