Using the Date object in Javascript

The native Date object in Javascript enables the date and time related actions in Javascript. The values inline with the UNIX epoch, meaning that it is based on the the number of milliseconds elapsed after 1970.01.01 0000 hrs UTC. However since the Javascript code is executed in the local web browser, the values are related to the local time of the computer where the code gets executed.

The object has following constructors:

Date( ) – creates a date object with current date and time values.
Date(Year, Month, Date, Hour, Minutes, Seconds, Milliseconds) – creates a date object with the specified values
Note month starts from 0, January is 0 while December is 11 and all the parameter of the constructor are optional.

Check the following examples:

let datenTime = new Date();
console.log("Current Time : " + datenTime);

let passedDatenTime = new Date(1990, 3, 28, 0, 0, 1, 30);
console.log("Passed Time : " + passedDatenTime);

let futureDatenTime = new Date(2024, 5, 2, 12, 30);
console.log("Future Time : " + futureDatenTime);

Output

Current Time : Tue Apr 28 2020 08:24:32 GMT+0530 (India Standard Time)
Passed Time : Sat Apr 28 1990 00:00:01 GMT+0530 (India Standard Time)
Future Time : Sun Jun 02 2024 12:30:00 GMT+0530 (India Standard Time)

Once the object is created, the parameters can be extracted using the following methods.

let datenTime = new Date();
console.log("Current Year : " + datenTime.getFullYear());
console.log("Current Month : " + datenTime.getMonth());
console.log("Current Date : " + datenTime.getDate());
console.log("Current Hour : " + datenTime.getHours());
console.log("Current Minute : " + datenTime.getMinutes());
console.log("Current Seconds : " + datenTime.getSeconds());
console.log("Current Millisecond : " + datenTime.getMilliseconds());

Output

Current Year : 2020
Current Month : 3
Current Date : 28
Current Hour : 8
Current Minute : 30
Current Seconds : 37
Current Millisecond : 809

Note that the current month value is 3, because it starts with 0. Therefore 3 means April.

Another important method is .getTime( ) which returns number of milliseconds from 1970.01.01 0000 hrs UTC. It is useful to calculate duration. For example, following illustrates calculating time taken to execute a code fragment.

timeConsumingJob();

async function timeConsumingJob() {
    let start_time = new Date();
    await sleep(2000);
    let end_time = new Date();
    let duration = end_time.getTime() - start_time.getTime();
    console.log("Duration = " + duration);
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

Reference

https://www.ecma-international.org/ecma-262/5.1/#sec-15.9

Case-Sensitivity of Programming Languages

Programming languages such as C, C++, Java, Python, GoLang, BallerinaLang are case sensitive languages. In simple terms, for these languages the case of the characters (simple or capital) does matter. For the mentioned languages speedOfLight and speedOFLight are two different variables. On the other hand programming languages such as Pascal, Basic (Visual Basic), Fortran, SQL, Lisp are case in-sensitive. Meaning, the case of the characters does not matter.

Visual Basic was the first programming language I learnt and then moved to C. At that time the concept of case sensitivity was bit confusing. As I felt, the readability was severely impacted. But after working with languages like C++, Python, GoLan, I think the case sensitivity is a feature which is good to have.

I think nobody except the creators of the programming languages can reason out why some of these languages are case-sensitive and some are not. Those days, most of the programmers were from Unix/ Linux background and Unix/ Linux are case sensitive. May be it could be one of the reasons. Early days, the resources, the computation were expensive and limited. Therefore the programmers were forced to produce less ambiguous code. This could be one of the reasons as well. Lot of programmer are fans of Hungarian notation. Case sensitivity support this notation. Because in this notation, identifiers starts with a lower case character and then upper case characters are used to indicate another word instead of using underscores. For example speed_of_light is to be represented as speedOfLight in the Hungarian notation. These are the reasons I can think of for the moment.

Gone are the days processing power was a limitation, therefore modern programming languages can relax this rule. But is it worth? Some could argue for and some could argue against. The feeling is personal rather than technical, though. Some argue case sensitivity directly relates to faster compilation time. Theoretically this is true. As the number of steps increase to resolve the ambiguity when case is not considered. But I m sure there can be better ways to improve the performance and with the powerful processors, this delay is negligible. The case sensitivity is hard to be managed in the code as there should be an extra effort to maintain it. However this is not an issue as the IDEs (Integrated Development Environments) are taking care of this extra work. I think that is the biggest reason why programmers do not notice case sensitivity as a big issue. Moreover, the case sensitivity is used a way of preserving the consistency in the code. For an example, rarely someone use two variables as unitObject and UnitObject (using the case sensitivity to differentiate names of the identifiers), because they can do so, even though it is syntactically correct. When the case sensitivity is in action,  the identifiers should be same in everywhere in the code which is a plus point when consistency is considered.

Most of the programmers coming from the case in-sensitive languages could complain over the case sensitivity as it is bit difficult to adjust. But it seems like the case sensitivity offers tight control over the consistency of the code and actually it increases the readability even though the feeling is otherwise. After all, this is something the creators of the programming languages should decide. For the moment, I think having case sensitivity is more advantageous, famous and sought than the other option.

What is your oppinion?

 

 

Presidential Election 2019 Results – Analysis using Python

Election to select the 7th Executive President of Sri Lanka has been concluded recently. If you are interested in analyzing the results and seeking for data, following Python script would be useful to you. Please check the repository to get the code. Results are organized in Electoral District level. Sri Lanka is divided into 22 Electoral Districts and 2018 Registry of Electors were used in this election.

Code Repository : https://gitlab.com/bckurera/pres-election-19

Refer to the following example to understand how to use the module, prez_2019_ed_res

import prez_2019_ed_res as db

FORMAT_F_NUM = "5,.2f"
FORMAT_I_NUM = "9,d"

##Find out the district in which SLPP secured the highest votes (precentage/ count)##
def find_max_votes_per_party(p):
    obj = db.prez_2019_ed_res()

    for party in p:
        valid_votes = obj.get_column("Valid")
        votes_for_slpp = obj.get_column(party)

        temp_prec = 0
        temp_count = 0
        temp_prec_dist = ""
        temp_count_dist = ""

        for x in votes_for_slpp.keys(): 
            p = votes_for_slpp[x] / valid_votes[x]

            if(p > temp_prec):
                temp_prec = p
                temp_prec_dist = x

            if(votes_for_slpp[x] > temp_count):
                temp_count = votes_for_slpp[x]
                temp_count_dist = x

        print(party, " highest %     - ", format(temp_prec*100, FORMAT_F_NUM) , " % -", temp_prec_dist)
        print(party, " highest count - ", format(temp_count, FORMAT_I_NUM) , " votes -", temp_count_dist)

##Highest voters - turnout##
def voters_prec():
    obj = db.prez_2019_ed_res()

    valid_dist = obj.get_column("Valid")
    rejected_dist = obj.get_column("Rejected")

    res = {}

    for x in valid_dist.keys():
        p = rejected_dist [x] / (valid_dist[x] + rejected_dist [x])
        p = round(p, 4)
        ext = {p: x}
        res.update(ext)

    for x in sorted(res.keys(), reverse = True):
        print(" Rejected % - ", format((x*100), FORMAT_F_NUM), " - ", res[x], " count - ", format(rejected_dist[res[x]], FORMAT_I_NUM))

##Two Party world##
def two_party_analysis():
    obj = db.prez_2019_ed_res()

    slpp_votes = obj.get_column("SLPP")
    ndf_votes = obj.get_column("NDF")
    others_vote = obj.get_column("Others")

    res = []

    for x in slpp_votes.keys():
        if(slpp_votes[x] < (ndf_votes[x] + others_vote[x])):
            res.append(x)

    for x in range(0, len(res)):
        dist = res[x]
        combined = (ndf_votes[dist] + others_vote[dist])
        print("Combinely Secured - ", dist, " combined count - ", (combined), " % - ", format((slpp_votes[dist]/(combined))*100,FORMAT_F_NUM ), " %")


party = ["SLPP", "NDF"]
print("\n----------------------------------")
find_max_votes_per_party(party)

print("\n----------------------------------")
voters_prec()

print("\n----------------------------------")
two_party_analysis()

 

IFS Labs – BrkTheCode Challenge

An interesting puzzle was published by IFS Labs in http://brkthecode.com/ recently. Here is how I broke it. Gave it a try for fun and thought of sharing as the challenge is already closed.

Puzzle

It is required to distribute item X (in discrete unit sizes) among number of items of Y based on few rules considering a property Z of item Y. The goal is to find the minimum amount required for item X. Refer to the READ_ME file, for more explanation of the puzzle.

Solution

This is not a np-hard problem, therefore use of heuristics would be faster and simpler to solve the puzzle.

The solution can be found in the following repository, implemented in C++.

https://gitlab.com/bckurera/brkthecode

Disclaimer

The puzzle might be copyrighted. Please contact http://brkthecode.com/ for more queries.
The content of the src directory is in the Public Domain meaning that it is copyright-free.

C++ Preprocessor Directives

In C++, a source code needs to be compiled to produce an executable. Once the compiler is invoked, the C++ preprocessor kicks in. As the name suggests, this program is responsible for preparing the source code before it meets the compiler. Preprocessor directives are used to instruct the preprocessor on what actions to be performed. Such directive is followed by # and directives can be included anywhere in the program.

Macro – #define

This directive is used to define a term which can be easily replaced. The syntax is as follow:

#define identifier replacement

The preprocessor matches the identifier and it will be replaced by the replacement. Replacement can be anything, a value, an expression, a statement, block statement. Preprocessor does not care what the values are. It just substitute values with no C++ syntax validation.

File Inclusion – #include

This directive is used in almost all the C++ source codes, even in the very first Hello World program. You should encounter the following line at the very beginning of a C++ source code, #include <iostream>

Using #include directive, the preprocessor is instructed to include the mentioned file to the source code. The preprocessor seeks the mentioned file and the entire content of the file is included in the source code. Standard I/O functions are defined in the file iostream.h and that is why this file is included in C++ program all the time.

There are two ways of achieving the file inclusion.

Use of < > – Angle brackets are used to instruct the preprocessor to seek the file in the standard include directories.  This is used to include files defined by the compiler most of the time.

Use of ” “ – Double quotes are used to instruct the preprocessor to seek the file in the given location relative to the location of the source code file, however if the file is not found, the preprocessor might check the standard include directories as well. This is why the standard I/O file can be included as #include <iostream> or #include “iostream”

Conditional Compilation – #ifdef #endif

This directive is used to compile statements conditionally within the code. The syntax is as follow:

#ifdef identifier
    statement(s)
#endif

Note that if the identifier is defined as a macro only the statements are getting compiled. The value of the defined macro does not important. If it is the case however, instead of #ifdef, #if needs to be used. However when #if is used, the macro has to be defined with a value. The #if directive checks the value of the macro.

#include "iostream"

#define DEBUG 1
#define Area
#define AREAFUNC x * y

int main(){

    int x = 10;
    int y = 5;

    #if DEBUG == 1
            std::cout << "Debug : X = " << x << "/ Y = " << y << std::endl; 
    #endif 

    #ifdef Area 
        if((x > 0) and (y > 0)){
            std::cout << "Area is - " << AREAFUNC << std::endl;
        }
    #endif

    return 0;
}

The above example covered all the directives discussed in the post.

Changing the address bar URL without reloading the web-page

Few months back, I came across a requirement where the browser address bar needs to be updated as the page is being scrolled. The same effect, I have recently observed in the Nike’s website. If you want to experience the same, visit the following link. Note the URL in the address bar gets updated as the page is being scrolled.

in HTML5, it costs one line of code to achieve this effect.

history.pushState()

This method is supported by many modern browsers. The exact signature is as follow:

history.pushState(state, title, url);

state – Any object that can be serialized, in Chrome it can be a null object as well (typeof null in Javascript is object)
title – The title of the page but Chrome choose to ignore the value anyway, therefore it can be null too.
url – This seems to be the only important parameter in this function. Abstract or relative URL can be supplied, however the root of the URL (domain) cannot be changed.

Here is an example:

<html>
<head>
<script type="text/javascript">
	function ChangeUrl(url) {
		history.pushState(null, null, url);
}
</script>
</head>
<body>


<div>
Click the buttons below and observe the browser address bar:
		<input type="button" value="Change URL 1" onclick="ChangeUrl('change_url.php');" />
		<input type="button" value="Change URL 2" onclick="ChangeUrl('change/change_url.html');" />
		<input type="button" value="Change URL 3" onclick="ChangeUrl('http://localhost/home.html');" />
</div>


</body>
</html>

Button one changes the URL appending the value of the parameter to the existing URL. Second button does the same. Third button uses abstract URL. It replaces the URL in the address bar rather than appending the value.

It is not possible to change the root. In this case, I m using the localhost. When providing the abstract location, it should remain same. No other URL with different root cannot be used. Using history.pushState creates a new history entry. However the providing URL should not exists as the browser doesnt loading the URL. It just changes the address bar and enter a history entry.

Proper Javascript function is mentioned below:

<script type="text/javascript">
	function ChangeUrl(title, url) {
		var obj = {Title: title, URL: url};
		history.pushState(obj, obj.Title, obj.URL);
}
</script>

With the creativity this feature can be used effectively.

Technical Paper – Intelligent MRP

Accepted for IESL 113th Annual Sessions 2019

Fuzzy Rule-Based Finite Capacity Planning Implementation of MRP for Discrete Manufacturing Environments

Corresponding Author : Buddhika Kurera (bckurera@geneai.edu.lk)

Abstract – Discrete Manufacturing is a term commonly used to identify manufacturing processes which produce items that can be counted, tracked as units. One of the common challenges in manufacturing industry is the production planning. As a result, many methods have been invented over the years to solve the planning problem optimizing the schedules. In such methods Material Requirement Planning plays a major role as it calculates the demand and supply beforehand. However, the fact of ignorance of capacity constraints in classical MRP to simplify the problem, leads to undesirable outputs when it comes to real-life scenarios as assumptions fails. The main issue in finite capacity planning approach is the complexity of the problem. As the number of variables and constraints grow, the complexity of the MRP calculation increases exponentially. In this research the main focus is to implement an effective mechanism to manage the problem. For the purpose, a fuzzy rule-based approach has been studied. Fuzzy logic is not a strange concept in scheduling. In fact, when data is not certain, usage of fuzzy logic would be an excellent choice. However, in this research fuzzy logic has been used to improve the efficiency, hence reducing the complexity of the problem. A model has been proposed to achieve the objective. Simulations based on numerical analysis have been carried out to fine tune the model based on benchmark problems afterwards.

Keywords: Discrete Manufacturing, Material Requirement Planning, MRP, Fuzzy rule-base, Fuzzy

Vectors in C++

Vectors in C++ is an interesting data structure which is bit similar to arrays. Not having a fixed size is the main difference though. The vector class is in C++ std namespace.

Vectors are associated with some useful methods which are handy in controlling vectors. Refer to the guide for more info.

Method push_back( ) to be used to add elements to a vector. Accessing an element can be done through accessing the relevant index as in arrays. size( ) gives the number of elements in a vector.

Defining a Vector

Creating an instance of the vector class.


#include <iostream>
#include <vector>

using namespace std;

int main()
{
   vector<string> names;
   
   cout << "Size of the vector : " << names.size() << endl;
   return 0;
}

Assign Values to a Vector


#include <iostream>
#include <vector>

using namespace std;

int main()
{
   vector<string> names;
   names.push_back("Alex");
   names.push_back("Bob");
   
   cout << "Size of the vector :" << names.size() << endl;
   cout << "First Name :" << names[0] << endl;
   
   names[0] = "Alex the great";
   
   cout << "First Name :" << names[0] << endl;
   
   return 0;
}

Example

Here is an example on how vectors can be used to solve a problem.

Write a function that accepts an upper bound positive integer and then calculate all the prime numbers within the given integer (excluding). Prime number set should starts with 2 in the index = 0.


#include <iostream>
#include <vector>

using namespace std;

vector<int> get_primes(int num);
bool is_prime(int num);

int main()
{
   vector<int> output;
   output = get_primes(20);
   
   for(int j=0; j < output.size(); j++){
       cout << "Prime No at index - " << j << " = " << output[j] << endl;
   }
   
   return 0;
}

vector<int> get_primes(int limit){
    vector<int> primes;
    for(int i = 2; i < limit; i++){
        if(is_prime(i)){
            primes.push_back(i);
        }
    }
    return primes;
}

bool is_prime(int num){
    for(int i = 2; i<num; i++){
        int r = num % i;
        if(r ==0){
            return false;
        }
    }
    return true;
}

Output

Prime No at index - 0 = 2
Prime No at index - 1 = 3
Prime No at index - 2 = 5
Prime No at index - 3 = 7
Prime No at index - 4 = 11
Prime No at index - 5 = 13
Prime No at index - 6 = 17
Prime No at index - 7 = 19

The code is self-explanatory. Notice how vectors are used in methods. Assigning values and accessing the indexes.

Coding Challenge #1 – Sum of multiples

Here is a little coding challenge to try.

The objective is to find the sum of multiples within a given range.

For example assume that given multiples are 4, 5 and 7. The upper limit is 20 (excluding). Multiples of 4 within 20 are 4, 8, 12 and 16. Then multiples of 5 within 20 are 5, 10 and 15. The multiples of 7 within 20 are 7 and 14. The objective is to find the sum of all those numbers.

The upper limit and the number of multiples can be vary from problem to problem.

Solution in Cpp

#include <iostream>

using namespace std;

int isMult(int mult[], int n, int length);

int main () {
    int no_of_mult = 2;
    int multiSet[no_of_mult] = {3, 5};
    int upper_limit = 10;
    
    int sum = 0;
    for (int i=0; i &lt; upper_limit; i++){
        sum = sum + isMult(multiSet, i, no_of_mult);
    }
    cout &lt;&lt; "Sum = " &lt;&lt; sum;
}

int isMult(int mult[], int n, int length){
    for(int i =0; i &lt; length; i++){
        int r = n % mult[i];
        if(r == 0){
            return n;
        }
    }
    return 0;
}

Try it online http://tpcg.io/ujmQDD