Javascript Tutorial Object.assign()

Many times you have an object and you want to clone or combine property of different objects to one object.

Let’s check how to do that with Object.assign().

The syntax of Object.assing is:

Object.assign(target, ...sources)

Suppose we have one object like the following:

let Employee = { name : 'Pietro', age : 44, Sex : 'male'};

We have also another object called EmployeeRecord which is as the following

let EmployeeRecord = {
name : 'Pietro', address : 'Colorado Avenue 45 Miami', seriority : 15, category_employee : 'Cat A'
};

Now we want to have a new object (t) which combines all properties of Employee and EmployeeRecord we can use the following command:

let t = Object.assign(Emnployee,EmployeeRecord)

Here is what will happen if we print to console the 3 objects above

As you can see if we print the new object “t” to console we can notice that this object has all the properties of the first object (Empployee) and also all properties of the second object (EmployeeRecord)

It is important to know that if one property has different value the property of the last object will overwrite the property of the first one.

We can verify that by changing slightly our previous example

let EmployeeRecord = {
name : 'Pietro2', address : 'Colorado Avenue 45 Miami', seriority : 15, category_employee : 'Cat A'
};

In this case the name property if different from the two objects.

If we re-run create a variable t and we assign both Employee and EmployeeRecprd

Please notice that now the name property is not Pietro but Pietro2.

C Tutorial – Pointers

Pointers vs Arrays : are the same?

In this post we will take a look at the difference between Pointers and Arrays.

Pointers and Arrays are not the same thing but there are a lot of common syntax that you can use

The biggest thing that they have in common is that both are sequence of memory address that you can access.

Let’s have a look at the array: you know that when you pass a variable by value to a function what happen is that the C Compiler makes a copy of the local variable in the stack and pass the copy to the function. Although both variables have the same value their memory address is different: in other words they are located in a different section of the memory.

Now when you pass one array as a value to a function the C compiler does not copy the whole array in the stack: that would be very inefficient. The C compiler will copy only the address of the first element.

That is a bit similar to what happen with a pointer where the C compiler move through the memory blocks starting from the first bloc.

Let’s have a look at an example. We declare an array of for elements and we fill with some integer values.

int myarr[4];
myarr[0]=20;
myarr[1]=40;
myarr[2]=60;
myarr[3]=80;

Now let’s print the memory location of the array. There are several way of doing that. We can do this way

 printf("This is the memorry address of array using myarr     %p\n",myarr);

Notice please: We have an integer array but we are asking to print the memory address with printf using the a format specifier p!:Format specifier p is used to “writes an implementation defined character sequence defining a pointer” (source https://www.programiz.com)

Now we can also print the memory address of the integer pointer using a different syntax

printf("This is the memorry address of array using &myarr    %p\n",&myarr);
    printf("This is the memorry address of array using &myarr[0] %p\n",&myarr[0]);
    printf("This is the memorry address of array using &myarr[1] %p\n",&myarr[1]);
    printf("This is the memorry address of array using &myarr[2] %p\n",&myarr[2]);
    printf("This is the memorry address of array using &myarr[3] %p\n",&myarr[3]);

This will return the following values. Notice please: that if we do not pass the element of the array the Compiler (first printf statement) will return the address of the first element (this is similar to what happen with a pointer)

Now let’s suppose we want to have a pointer to the array

 int *pointerArray;
 pointerArray=myarr;

Let’s print the memory address of the pointer at different location

printf("\n");
    printf("------How to move between memory address of the pointerArray---------:\n");
    printf("This is the memorry address of the pointerArray base      %p\n",pointerArray);
    printf("This is the memorry address of the pointerArray+1         %p\n",pointerArray+1);
    printf("This is the memorry address of the pointerArray+2         %p\n",pointerArray+2);
    printf("This is the memorry address of the pointerArray+3         %p\n",pointerArray+3);

Those instruction will print all the memory blocs of the array

If I want to know the value of first element of array I can de-reference with the following standard command to de-reference the pointer

printf("This is the memorry address of the *(pointerArray+1)      %d\n", *(pointerArray+1) );

But I can also use (notice please) the array’s way to de-reference the pointer

printf("This is the memorry address of the pointerArray[1]        %d\n",pointerArray[1]);

The result will be exactly equal, in this example 40.

Once I have a pointer we can say that pointer is equal to an array. This expression is valid. However we cannot say that array is equal to pointer.

Here is the code of the example above

C Tutorial – Pointers

C Array of Pointers

Array of Pointers are very useful in C, especially when you deal with Strings.

Let’s review a small example.

We start declaring a array of pointer as follow:

char *mylist[] = {
        "Java",
        "C",
        "Python",
        "Javascript",
        "Java"
    };

We also want to declare a variable type integer that we will use later.

int yourselection;

In our example we will give the user the option to select the programming language that is like the most.

 printf("What do you like programming\n");

    printf("0:Java\n");
    printf("1:C\n");
    printf("2:Python\n");
    printf("3:Javascript\n");

    printf("Please enter your selection:");

Now we ask the user to select one option:

printf("Please enter your selection:");
    scanf("%d",&yourselection);
    printf("%s\n",mylist[yourselection]);

In the code above we read the option provided by the user and then we print it out as shown in the figure below:

If you notice we call the array of pointer “mylist” and we pass the parameter that the user has selected.

Using array of pointers has also one benefit especially when dealing with strings: we can compare easily between 2 strings without need to check character by character the string nor we need to use the library function strcmp

Let’s view a practical application of that. Once the user selected is option the program will check if the user like C the most or not and print a different statement.

Here is the code:

 if (mylist[yourselection]==mylist[1]) {
        printf("You selected C, Congratulation\n");
    }

    else{
          printf("You have selected %s", mylist[yourselection] );  
          printf(" which is not my favorite\n");
        }

Here is what happen if we select Java for example

As you can see we were able to compare strings very easily without going character by character.

Here is the full program

C Tutorial – Pointers

C Dynamic Integer Array using Pointers

This is a small tutorial on how to create a Dynamic Integer Array in C using pointers.

Python and Javascript have their own to add an element to an array.

In C static array do not have the possibility to change the size of an array.

However if we use Pointers we can achieve the some functionality.

Let’s review an example together.

We start our example by declaring an integer pointer and allocating 20 blocks of memory. We do that using the malloc command.

 int *a=(int*)malloc(20 * sizeof(int));

We also want to declare a second variable type integer

int b;

At this point we can first fill the pointer with an integer value

  // Fill the pointer
    for (int i =0; i<20; i++) {
        a[i] = i+1;
    }

If we loop through this pointer we will can print all its value that will range from 1 to 20.

Now let’s suppose that the user wants to change the size of the pointer.

 //Ask the user an input
    printf("\n");
    printf("Please give me one number:");
    scanf("%d",&amp;b);
    printf("%d\n",b);
    

So we ask the user to give a number and we store the number in the variable integer b.

Now let’s resieze the pointer using realloc : so in fact we re-allocate memory to our pointer.

 //Reallocate memory of the pointer a
    a=realloc(a,b*sizeof(int));

Let’s fill the array too with the integer value as we did before

 //Fill the array
    for (int s =0; s<b; s++) {
        a[s] = s+1;
    }


    // Reprint the pointer
    for (int s =0; s<b;s++)   {
        printf("%d ", a[s]);
    } 

Let’s run the code to check how the program

Running the C Program

You can download the whole example here

A Javascript Game

Let’s review now the Javascript code behind this small game.

First of all our little program define 4 elements:

One array called myarr

myarr={
    "it-flag.gif":"Italy",
    "tn_fi-flag.gif":"Finland",
    "tn_mx-flag.gif":"Mexico",
    "po-flag.gif":"Portugal",
    "ja-flag.gif":"Japan",
    "tn_us-flag.gif":"USA",
    "tn_ro-flag.gif":"Romania",
    "pl-flag.gif":"Poland",
    "tn_gm-flag.gif":"Germany"
};

This array contain all the flags that are loaded in the game.

We also define 3 elements more that will be accessible from any function of the program

randomNmber=0;
completedList=false;
var score=0;

Now the first function that we review is called startGame()

function startGame() {
    getNextEntry();
    document.getElementById("sourceimg").src=defineCandidate(randomNmber);

    if (completedList==true) {
        document.getElementById("sourceimg").src="win.gif";

    }
}

The first line of the function call the function getNextEntry. This is a function that define a random number. The function is below

function getNextEntry(){
    const val = Object.keys(myarr);
    max = val.length;

    if (max==0) {
        listTerminated()
        completedList=true;
    }

    else {
        randomNmber=Math.floor(Math.random()*max ) + 0;
    }

This function first get all the keys from the array myarr.

If we print to console the val object we will see that the array is a collection of all the flags loaded.

Array(9) [ “it-flag.gif”, “tn_fi-flag.gif”, “tn_mx-flag.gif”, “po-flag.gif”, “ja-flag.gif”, “tn_us-flag.gif”, “tn_ro-flag.gif”, “pl-flag.gif”, “tn_gm-flag.gif” ]

The variable max get the current lenght of the array

If the array is equal to zero than the user has won: in this case the program will call a listTerminated function that will print out the congratulation message for the player.

If the array is greater than zero then a random number is generated. The global variable (randomNmber) will be assigned a random number

Let’s go back to the function startGame.

In the html page we have a an image tag has the one below

Image Tag

Now we need to insert the randomly chosen flag in the image tag.

To do so we call the function defineCandidate(randomNmber) and we pass the random number as a parameter.

Let’s have a loo at the defineCandidate function.

//Return first Key of the Object
function defineCandidate(num){
    const keys= Object.keys(myarr);
    return keys[num];
}

If we console out the keys[num] the result will be :

Passing from number to file name.

As you can see anytime we press Start Game the function defineCandidate will receive a number as parameter and return the key (which in this case consist in the name file of the picture).

So far we have seen how to choose randomly a number from the Flag Array (myarr) and then pass the number to a function that will give us the name of the picture to insert in the img tag.

Let’s check now what happens when the user actual select the answer from the list of values and hit the confirm button.

As usual first the function and then the explanation

function okconf(){
    var userSelection=document.getElementById("Country")
    var countrySelected=userSelection.options[userSelection.selectedIndex].value;
    let flag_posted= myarr[defineCandidate(randomNmber)];

    if (flag_posted==countrySelected) {
        addscore();
    }

    else {
        removescore()
    }

    updateLOV(defineCandidateValues(randomNmber));
    removefromselection(flag_posted);
    startGame();
    
}

When the user hit the button “Confirm” the function okconf() is called.

First of all a variable userSelection is generated: this variable is populated with the drop down list of value. Let’s have a look at what happen when we press confirm and console out the userSelection variable.

userSelection variable returns the drop down menu

At this point we need to get the value actually displayed in the drop down (in the picture above we need to get Finland).

To do so:

countrySelected=userSelection.options[userSelection.selectedIndex].value;
We use the selectedIndex command from the drop down menu to get the value of the country chosen by the user.

At this point we know that the user has selected one country (for example Finland).

We need to check if the answer from the user is equal to the flag displayed.

We still have our randomNumber referring to the array. So all we need to do is get the value from the array dictionary

Once this is done we can check if the answer provided by the user is correct or not. If it is correct we will call addscore, otherwise removescore

The functions addscore and removescore are self-explanatory.

Let’s instead keep going with our function okconf.

After updating the score the function call the function updateLOV. This function receive as a parameter the name of the country displayed.

//Remove item from list of values in the webpage
function updateLOV(mycountry){
    mylist=document.getElementById("Country");
    console.log(mylist);
    for (i=0;i<mylist.length;i++) {
        if (mylist[i].value==mycountry) {
            mylist.remove(i);
        }
    }
}


The function above assign to mylist the selection list of values. So mylist is a type array with all the values

Then the function start a loop inside the array mylist and check if the value of the list is equal to the name of the country received as a parameter. If that is the case from mylist the value of the country is removed.

So far we have removed from the list of value the name of the country displayed. We need also remove the country selected from the global array

We do so with the function below

//delete the item from the object 
function removefromselection(flag_posted) {
    item_to_remove=defineCandidate(randomNmber);
    delete myarr[item_to_remove];
    //console.log(myarr);       
}

Pie Charts

In this section we will be looking at Pie charts. Let’s see a small example. Suppose that we want to chart the distribution of active hours for a standard day.

Let’s suppose that 70% of the active hours are taken by work and than the rest of the day is equally split between Programming, Reading and Sport (that is how much I can at the moment).

Let’s have a look at the code below:

import matplotlib.pyplot as plt
l=["Work","Sport","Programming","Reading"]
mytime =[70,10,10,10]
e=(0,0,0.2,0)
fig1,ax1=plt.subplots()
ax1.pie(mytime, explode=e,labels=l,autopct="%1.1f%%",shadow=True,startangle=90)
ax1.axis('equal')
plt.title("Day Distribution")
plt.show()

We have a variable for the Label (l) and a variable with the hours distribution.

The variable “e” is used to indicate MatPlot which slice of the Pie we want to detach from the Pie (in this case we are selecting the Programming element (the third in the list)

The other important part of this small program is the ax1.pie where we insert the :

  • values to plot (mytime variable)
  • we set the explode flag so that we can detach the 3rd element of our list
  • the label (variable l)
  • the format of the data (autopct)
  • shadow paremeter is set to True
  • startangle set to 90

Here is our Pie Chart

Plotting Horizontal Bars

In this post we will review how to plot horizontal bars using MatPlot

Let’s put the code first

import matplotlib.pyplot as plt

items=["Radio","Television","Phones","PlayStation"]
sale_units=[400,100,200,600]

plt.figure(figsize=(10,4))
plt.barh(items,sale_units,color="green",label="Sales by Cat")
plt.xlabel("Sales Units")
plt.ylabel("Sales Category")
plt.text(500,1,"Price Dropped",fontsize=14, color="blue")
plt.text(100,3,"Stock Issue",fontsize=14, color="red")
plt.legend(loc="best")
plt.title("Sales by Category")
plt.show()

As you can see we can establish the size of the figure and adjust the size of the figure we the command plt.figure(figsize=(X,Y))

To draw horizontal bars we use the command plt.barh()

One interesting thing is the possibility to add specific comment to the plot area to facilitate the understanding from the user.

We can achieve that using the command plt.text where we first establish the position of the command, then the text we want to show and then we can format the text by specifying font size and color.

Plotting Vertical Bars

Let’s have a look at how to Plot Vertical Bars using MatPlot Lib

In this example we imagine that we have to represent the sales of 4 categories of items: “Radio”,”Television”,”Phones”,”PlayStation”

We also know that each of this categories has sold respectively : 400,100,200,600 units.

Let’s have a look at the code:

import matplotlib.pyplot as plt
items=["Radio","Television","Phones","PlayStation"]
sale_units=[400,100,200,600]
plt.bar(items,sale_units,color="blue",label="Units by Cat")
plt.title("Sales by Category")
plt.xlabel("Category of Goods")
plt.ylabel("Unit Sales")
plt.legend(loc="best")
plt.show()

As you can see in line 4 we represent categories of item (Axis X) and sale units (Axis Y). We also add that the label that describes better the content of the graph.

As we have defined a label we can now implement a new function (plt.legend). This function needs as a parameter represented by the location. Right now in this example we will tell the program to put the legend into the best location.

Finally we show the graph calling the function plt.show()




MatPlot Library

In this section we will look at how to plot series using Matplot Library.

Let’s suppose that we have a series with the following value : 200,400,600,800,800.

Those values relates to the month 2 (Feb), 4 (Apr), 6 (June), 8 (Aug) and 10 (Oct)

We want to represent the series using MatPlot.

Below the code that we have to write:

import matplotlib.pyplot as plt
plt.plot([2,4,6,8,10],[200,400,600,800,800])
plt.xlabel("Months")
plt.ylabel("Spent USD")
plt.title("Representing a Series of Data")
plt.show()

As you can see we define a plot which will contain the X and Y respectively

We can set the label using the command plt.xlabel(“some text”) or pltylabel(“some text”).

If we want to add a tile the command to use is plt.title(“Add your title here”)

Finally we show the plot with the command plt.show()

Ok we have plotted a line but what happens if we need to plot more lines and we need to put a legend and we want to format the lines in a different manner?

Let’s have a look at a more complicated example

import matplotlib.pyplot as plt

plt.plot([2,4,6,8,10],[200,250,300,400,550],'b--',label="Revenue")
plt.xlabel("Months")
plt.ylabel("Units Sold")
plt.plot([2,4,6,8,10],[150,200,210,260,360],'r:',label="Cost")

plt.title("Representing a Series of Data")
plt.legend(loc="best")
plt.show()

As you can see now we have two lines and a legend providing more information.

In comparison with the previous graph we have

  1. Added a sencond line
  2. Format the data choosing a different color for each line
  3. Chose a different style for each line

To format the line we have used a format string. Here is the link to the MatPlot WebPage which contains very useful information

Link