Wednesday, December 25, 2019

Deploying React App to Netlify

Typically we deploy ours react app locally. Now I am going to show you how to publish your react app to the internet.

You can use either Surge or Netlify. My preference is Netlify because whenever you update the source in Github, it automatically updates the internet site.

First, you need to create an account at Netlify and link your account to Github. At the dashboard, click on the "New site from git" button.

At the "Create a new site" page, click on GitHub. Select the repos you wish to publish.


Fill the setting. For react app, the setting will automatically be filled. Click on "Deployed site" once done.



Netlify will pull the source from Github and publish the site. An url will be generated as well.

My react todo application: https://laughing-snyder-9e6b8c.netlify.com/

References:

Tuesday, December 24, 2019

What is your first VS Code plugin?

Prettier enforces a consistent code style.



Other favourite plugins:

  1. Bracket Pair Colorizer
  2. Indent Rainbow
  3. Auto Rename Tag
What is your first VS Code plugin? Comment below.

Sunday, December 8, 2019

Quick Sort in Javascript

Quick sort is faster than bubble sort.

It uses the idea of divide and conquers. Divides the array into two halves using a pivot in such a way that elements in the left half are smaller than the pivot and elements in the right are greater than the pivot — then recursive using quick sort on the left and right parts.

I would recommend below youtube to understand Quick Sort:
https://www.youtube.com/watch?v=eqo2LxRADhU

Here is my implementation in javascript:
function quickSort(arr, start, end) {
  // Stop the recursion when the start equal or smaller to the end
  if (start >= end) { 
    return ; 
  };
  
  // Here is the magic happen
  let pivotIndex = partition(arr, start, end);
  
  // Recursion - quick sort the left part
  quickSort(arr, start, pivotIndex - 1);
  
  // Recursion - quick sort the right part
  quickSort(arr, pivotIndex + 1, end);
}

function partition (arr, start, end) {
  let pivotIndex = start; // Pivot location
  let pivotValue = arr[end]; // Use the last number  
  
  for (let i=start; i<end; i++) {
    // Move number that smaller than pivot value to the front.
    // Update pivot index
    if (arr[i] < pivotValue) {
      // Move to front
      swap(arr, i, pivotIndex);
      pivotIndex++;
    }
  }
  
  // Swap the pivot value to correct location
  swap(arr, end, pivotIndex);
  return pivotIndex;
}

function swap(arr, a, b) {
  let temp = arr[a];
  arr[a] = arr[b];
  arr[b] = temp;
}

let arr = [2 ,1, 4, 5, 3, 6, 6, 8, 1, 3];
quickSort(arr, 0, arr.length - 1);

Thursday, December 5, 2019

Bubble Sort in Javascript

Bubble soft is the most straightforward sorting algorithm that works by repeatedly swapping the elements if they are in wrong orders.

Example:

1. Swapping the first element.
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

2. Swapping the second element.
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), No swap
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap

3. Pass the sorting criteris when there is no swapping.
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ), No swap

Let write the code to do it:

let items = [1,2,3,5,4];

function bubbleSort(p_val){
  let sorted = p_val;
  
  for (let i=0, x=p_val.length; i<=x; i++){
      let isSwapRequired = false;
      for(let j=0; j<=x-i-1; j++){
        // compare items and only swap them if the second one's smaller
        if (sorted[j] > sorted[j+1]) {
          isSwapRequired = true;
          let first = sorted[j];
          let second = sorted[j+1];
          sorted[j+1] = first;
          sorted[j] = second
        }
    }
    // IF no two elements were swapped by inner loop, then break 
        if (!isSwapRequired) { break; };
  }
  
  return sorted;
}

document.write(bubbleSort(items));
The best case is when the array is already sorted, and worst case is the array is reverse sorted.

So that is the famous bubble sort. I will talk on other sorting algorithms next time.

Notes: There is a native javascript method to sort an array (Array.sort) that is more efficient and easier to use. This example is to demonstrate the bubble sort.

Wednesday, December 4, 2019

Recursion in Javascript

A recursive function is the ability to call itself and stop on matching the criteria.

For example, we could write a recursion to reverse a string from "ABC" to "CBA".

// Parameter: A string.
// Return: Last character of the string.

function reverseString(p_val){

  // Get the string's length
  var length = p_val.length;

  // Get the last character
  var lastchar = p_val.charAt(length - 1);

  if (length == 1) {

     // Return the last char
     return lastchar;

  } else {

    // Run the recursion
    return lastchar + reverseString(p_val.substring(0,length - 1))

  }

}

Let's say the parameter is "ABC". The process will be:
  1. Return: C + reverseString("AB") 
  2. Return: C + B + reverseString("A") 
  3. Return: C + B + A

Thursday, November 28, 2019

JavaScript: Define Multiple Instance in Module Pattern

In JavaScript: Module Pattern with Anonymous Closure article, I have shown you how to create a Module using Immediately-Invoked-Function-Expression (IIFE). With IIFE, you only can have a single instance of the object.

What if you need to have multiple instances? Example two armies carry different weapons.

Remove () in the ARMORY module in the previous Article.
var ARMORY = (function(){
  // Private
  var weaponList = [ * List of weapon object * ];
  var removeWeapon = function(...){};
  var replaceWeapon = function(...){};

  // Public
  return{
    makeArmorRequest: function(...){}
  }
});
Now you can create multiple instances:
var army1 = new ARMORY();
var army2 = new ARMORY();

Tuesday, October 29, 2019

If you are writing ES6 syntax in designer's script library, you will get an error - ""const is a reserve identified".









I think designer default to ES5 syntax checking.

To work around, you can write your javascript at "WebContent" folder using Package Explorer. For this example, I will put my javascript in "javascripts" folder.





















This is how you point the javascript:
  <script src"javascript/like_button.js"></script>

Reference:
https://hclpnpsupport.hcltech.com/csm?id=community_question&sys_id=3bc76f951bbc481877761fc58d4bcb5e

Thursday, October 24, 2019

Object Methods in Javascript

I have introduced "Merging Object via Object.assign()" in my previous article. In this article, I will go over other important build-in object methods.

Object.create()
Object.create() method is used to create a new object and link it to the prototype of an existing object.

Object.keys()
Object.keys() create an array containing the keys of an object.

Object.values()
Object.values() create an array containing the values of an object.

Object.entries()
Object.entries() creates a nested array of the key/value pairs of an object.

Object.assign() - I would like to mention again. :-)
Object.assign() is used to copy values from one object to another.

Object.freeze()
Object.freeze() prevents modification to properties and values of an object and prevents the property from being added or removed from an object.

Object.seal()
Object.seal() prevent new properties from being added to an object but allows the modification of existing properties.

Object.getPrototypeOf()
Object.getPrototypeOf() is used to get the internal hidden [[Prototype]] of an object, also accessible through the _proto_ property.

In this example, we can create an array and access to the Array prototype.
  const employees = ['Simon','Adam','John'];
  console.log(Object.getPrototypeOf(employees));
Output:












The output is showing the employee array has access to pop, find, and other array prototype methods.

This method can be useful to get information on the available prototype methods - String, Integer, and etc.

References: 
https://www.digitalocean.com/community/tutorials/how-to-use-object-methods-in-javascript

Monday, September 23, 2019

HCL Software Customer Support Site

HCL Software launched a new customer support site.

For HCL Customer, you can register at https://support.hcltechsw.com/csm?id=csm_registration

For others where you wish to take part in the community (Forum, Knowledge Base, Attend Community Event, etc.), you can register at https://support.hcltechsw.com/csm?id=community_external_user_registration

Wednesday, September 18, 2019

NodeJS - HelloWorld with ExpressJS

In this tutorial, you are going to learn how to create an express application using Express Generator and create a hello world page by creating a new route file in nodejs.

This tutorial tested on Nodejs v10.16.2 and Expressjs v4.16.1.

1. Install Express Generator. Create the application skeleton using application generator tool. Go to the project folder and type “npm install -g express-generator”

2. Create Express Project using EJS view engine. By default, Express is using PUG view engine. For this example, we are using EJS. Use this command “express --view="ejs" [folder name]” to create the express project. Example: “C:\Users\simon.siah\workspace>express --view="ejs" nodejs-expressjs-starter”.

















3. Install dependencies. Type below command to install dependencies. It will read the package.json and install the stuff.





4. Start the server Type below command to start the server.




5. Open a browser and type http://localhost:3000/.











6. Route files. - The route files store in folder routes. - This section in app.js define the http routes. - Example: /, is using routes/index.js and /users us using routes/user.js.

7. View files - The view files store in folder views.

8. Create a Hello World Page.
  • Copy the routes/index.js and paste into folder routes, rename the files to helloworld.js. 
  • Change the content below:
  • Create helloworld.ejs in views folder: 
  • Update app.js to include helloworld route:
     
  • Start the server and enter URL -> http://localhost:3000/helloworld 
Changing the EJS templates does not require a server restart, but whenever you change a JS file, such as app.js or the route files, you'll need to restart the see the changes.

I am using sublimetext as IDE to update the sources. It is free, and you can download here: http://www.sublimetext.com/ 

Here are some useful references: 

Node.js, Express.js, MongoDb Tutorial:  

Node.js: 

Express.js: 

Thursday, August 8, 2019

CRUD using Java Bean binding in XPages Part 2

The disadvantage of part 1 is overloaded getter/setter when there are many fields. In this part 2 example, I am going to introduce the model layer using data object. By using data object, you don't need to configure the getter/setter.

Also, part 2 has included doclock and data validation functionality.

Download the database here:
https://drive.google.com/open?id=1vWWvqNlVOtV-ftUpvKYK-XJMiVcmOb5y

Notesin9:
http://www.notesin9.com/2014/01/13/notesin9-133-using-java-in-xpages-part-2/

OpenNTF DocLock:
https://www.openntf.org/main.nsf/project.xsp?r=project/XPage%20Document%20Locker

Wednesday, July 31, 2019

CRUD using Java Bean binding (Getter / Setter) in XPages

It is build using Model-Control-View (MVC) architecture.
  • Model – Field binding, configure the getter/setter, and business logic.
  • Controller – Serving the request.
  • View – XPages for  UI and Form.

Download the database here:
https://drive.google.com/open?id=1ZTITEjvp_YNakEkUhFn05PCcRWd0olQF


Part 1 Includes:
  • Bootstrap 4 Theme
  • Create, Read, Update, Delete using Java Bean
  • Text Field
  • Date Field
  • Dropdown Field
  • Checkbox Field (Multiple Value)
  • Backend Computed Data

XPages and Managed Bean: a new way to process Notes documents:
http://blog.redturtle.it/2014/02/06/xpages-javabean-new-way-to-bind-notes-document

How to use Managed Beans in XPages:
https://docs.google.com/document/d/1XFXEmXH8KFcXEHcs2qvbWqOs_TqJWJ8Dbs9CMMKLszI/mobilebasic?pli=1

Notesin9:
http://www.notesin9.com/2013/12/17/notesin9-132-using-java-in-xpages-part-1/

Quick Java Course for XPages Developers:
https://docs.google.com/document/d/1jjZIvkGQWjwYfTJBGVaE_0CyOiskLeOJ_3vlOWUjVNk
https://docs.google.com/document/d/1IdhQvybM47EMUjC8WN8vOkeGyBrirjdOk_DYbeICHRU
https://docs.google.com/document/d/1gywwFtmAdgTtGJt-LxUbxaH0yJFtbQleJlLtWzZNZpI

Wednesday, July 17, 2019

Why I use Vanilla (Native) Javascript, not Underscore.js or Lodash?

Underscore.js and Lodash are javascript utility library written using functional programming. Lodash is the level up version from Underscore.js.  Most of its ideas and contributors are from Underscore.js. Both libraries used to be my favourite until ECMA 2016 where developers can code ECMA 2016 without using Underscore.js and Lodash. Here are a few examples:

const users = [
  { 'user': 'joey',  'age': 32 },
  { 'user': 'ross',    'age': 41 },
  { 'user': 'chandler', 'age': 39 }
]

// Native
users.find(function (o) { return o.age < 40; })

//lodash
_.find(users, function (o) { return o.age < 40; })

// Native
users.filter(function (o) { return o.age < 40; })

//lodash
_.filter(users, function (o) { return o.age < 40; })

// Native
users[0]

//lodash
_.first(users)

// Native
users.forEach((value, index) => { console.log(value) })

//lodash
_.each(users, (value, index) => { console.log(value) })
I am not here to against Underscore.js or Ladash. Whatever the decision, think about future maintenance and support, and speed.

Underscore.js and Ladash maintenance by public and no promise on the future roadmap. Vanilla javascript maintenances by various organizations involved Mozilla, Google, Microsoft, etc. Every year has a new release since the year 2015, the current version is ECMA 2019.

In term of speed, some methods in Ladash are faster than vanilla javascript because of functional programming.

https://underscorejs.org/
https://lodash.com/
https://en.wikipedia.org/wiki/ECMAScript
https://codeburst.io/why-you-shouldnt-use-lodash-anymore-and-use-pure-javascript-instead-c397df51a66
https://blog.bitsrc.io/you-dont-need-lodash-or-how-i-started-loving-javascript-functions-3f45791fa6cd

Wednesday, June 19, 2019

Servlet Implementation in Domino

In this article, I am going to show you how to implement the servlet in Domino. The implementation is using DesignerFacesServlet, not the tradition HttpServlet. The DesignerFacesServlet allows us to use the XPages scope variable.

1. Import servlet library into the database. The servlet library can find in <NOTES>\framework\shared\eclipse\plugins\com.ibm.domino.xsp.adapter_<VERSION>.

2. Create Servlet factory to map the URL “https://server/database/xsp/myservlet” to “test.servlet.HelloWorldServlet”.
package test.servlet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import com.ibm.designer.runtime.domino.adapter.ComponentModule;
import com.ibm.designer.runtime.domino.adapter.IServletFactory;
import com.ibm.designer.runtime.domino.adapter.ServletMatch;
public class ServletFactory implements IServletFactory {
      private static final Map<String, String> servletClasses = new HashMap<String, String>();
      private static final Map<String, String> servletNames = new HashMap<String, String>();
      private ComponentModule module;
    public void init(ComponentModule module) {
           System.out.println("TestFactory:init");
           servletClasses.put("myservlet""test.servlet.HelloWorldServlet");
           servletNames.put("myservlet""Hello World");
           this.module = module;
    }
    public ServletMatch getServletMatch(String contextPath, String paththrows ServletException {
        try {
                  String servletPath = "";
                  // iterate the servletNames map
                  Iterator<Map.Entry<String, String>> it = servletNames.entrySet().iterator();
                  while (it.hasNext()) {
                        Map.Entry<String, String> pairs = it.next();
                        if (path.contains("/" + pairs.getKey())) {
                              String pathInfo = path;
                              return new ServletMatch(getWidgetServlet(pairs.getKey()), servletPathpathInfo);
                        }
                  }
        } catch (Throwable t) {
            t.printStackTrace();
        }       
        return null;
    }
    public Servlet getWidgetServlet(String keythrows ServletException {
 return module.createServlet(servletClasses.get(key), servletNames.get(key), null);
    }
}
3. Enable servlet factory services.
3.1 Open the database in Package Explorer.
3.2 Go to folder “Code/Java/META-INF/services/ and create a text file name “com.ibm.xsp.adapter.servletFactory”.
3.3 In the text file, fill “test.servlet.ServletFactory” to enable the servlet factory.

4. Create the HelloWorld Servlet.
package test.servlet;
import com.ibm.xsp.webapp.DesignerFacesServlet;
import java.io.*;
import javax.faces.context.FacesContext;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorldServlet extends DesignerFacesServlet {
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponsethrows ServletException, IOException {
        // Set up handy environment variables
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        ServletOutputStream out = res.getOutputStream();
        FacesContext facesContext = this.getFacesContext(reqres);
        try {
            res.setContentType("text/plain");
            System.out.println("User hit the service.");
        } catch(Exception e) {
            e.printStackTrace(new PrintStream(out));
        } finally {
                  facesContext.responseComplete();
                  facesContext.release();
                  out.close();
        }
    }
}
5. Test the servlet by entering URL https://server/database/xsp/myservlet.




6. The implement is easy by creating three files.


Download Sample Database

References:
https://edm00se.io/xpages-servlets/servlet-implementation/
https://www.ibm.com/developerworks/cn/lotus/xpage-servlet/index.html