Friday, December 16, 2016

Thursday, December 15, 2016

Sunday, December 11, 2016

Monday, November 14, 2016

React Redux


React Router (react-router-dom)

To implement routing in a ReactJS application...


  • You need to install react-router-dom
  • Use the components BrowserRouter, Route, Switch, Link from react-router-dom module.
  • Define the routes and wrap them in BrowserRouter
  • Define the links
  • and you are ready to go. 

npm i react-router-dom --save











Recently stumbled across this blog which is an interesting read on react-router-dom:
https://blog.pshrmn.com/simple-react-router-v4-tutorial/



Found this tutorial loaded on GitHub which gives a simple beginning and escalates to advanced level.

I liked the first line in the tutorial..."At its heart React Router is a component, and its not going to display anything until you configure a route". Read and practice the tutorial...

https://github.com/reactjs/react-router-tutorial/tree/master/lessons/02-rendering-a-route

Another good example:

Friday, November 11, 2016

Using Node.js require vs. ES6 import/export

Read one of the postings on stackoverflow and it gave me that "a-ha" moment.

http://stackoverflow.com/questions/31354559/using-node-js-require-vs-es6-import-export

I am worried that I may lose this posting in stackoverflow so copying the question and answer from there to here for my future reference:


Question:

In a project I'm collaborating on, we have two choices on which module system we can use:

  1. Importing modules using require, and exporting using module.exports and exports.foo
  2. Importing modules using ES6 import, and exporting using ES6 export

Are there any performance benefits to using one over the other? Is there anything else that we should know if we were to use ES6 modules over Node ones?

Answer:

Keep in mind that there is no JavaScript engine yet that natively supports ES6 modules. You said yourself that you are using Babel. Babel converts import and export declaration to CommonJS (require/module.exports) by default anyway. So even if you use ES6 module syntax, you will be using CommonJS under the hood if you run the code in Node.

There are technical difference between CommonJS and ES6 modules, e.g. CommonJS allows you to load modules dynamically. ES6 doesn't allow this, but there is an API in development for that.

Since ES6 modules are part of the standard, I would use them.

Thursday, November 10, 2016

React Redux


  • redux provides an empty store where application state can be manufactured.
  • You tell the store what to create as the application state, how to update the application state (thru reducer)
    • store = Redux.createStore(reducer)
  • Reading from the application state in application is straight forward: 
    • store.getState()
  • Updating the application state is by triggering the update logic in the store by dispatching the actions.
    • store.dispatch({type: 'increase', graceMarks: 5})
  • NOTE: When you update a state, you don’t update the state but rather create a new state out of old state.
  • You can even subscribe to store to get the status on the updates.
    • state.subscribe(state.getState())
  • react-redux provides couple of additional facilities, Provider and connect.
  • Provider to provide the store to the root component.
  • Connect passes state, dispatch actions to child component. 
A sample using just redux:

// importing createStore from redux
import {createStore} from 'redux';

// Creating a reducer
const sampleReducer = function(state, action){
    if (!state){
         state = 0;
    }
    if (action.type === "INC"){
         state =  state + 1;
    }
    return state;
}

// Create a store. Passing in the reducer that i created above
const store = createStore(sampleReducer);

// subscribing to store to see the updates
store.subscribe(() => {
    console.log("state changed ", store.getState());
})

// start dispatching actions to store.
store.dispatch({type:"INC",payload:"something"})


There you go… You create a reducer, you create a store and then whenever you dispatch actions, the reducer or multiple reducers will act upon on that store. 

Sunday, October 30, 2016

JavaScript function call, apply, bind methods

"Say, you created a function. If you can stitch this function to an object, the function then can access that object that it's been stitched to. call, apply, and bind help you do that"

Explained in terms of a straw:


"Say, you have a straw. You haven't yet dipped it in any drink, so what is the drink that's flowing in the straw? Nothing. 

But if you dip the straw in juice and start drinking, what is the drink that is running through the straw? Whatever juice you dipped your straw in. 

Say, you added some essence to the juice, you gonna suck them too.

So...

Straw.call(juice) ...this is how you attach your function to an object.

Straw.call(juice, essence) ...this is how you attach your function to an object and pass parameters too"


Function is an object in JavaScript and it has some in-built methods like call, apply, bind.

A simple example to explain how a call method works:

var sayHi = function(){
      console.log("Hi " + this.name);
}

sayHi(); //returns crazy results as it gets confused with "this"

var person = {"name":"Ramesh"};

sayHi.call(person); // returns Hi Ramesh because person object becomes "this" inside sayHi function.

sayHi.apply(person); // returns Hi Ramesh because person object becomes "this" inside sayHi function.

var sayHiNewFunction = sayHi.bind(person); // creates a new function binding passed in object to "this".

Read this article http://hangar.runway7.net/javascript/difference-call-apply where the author explained about call and apply in such a simple way!!!

Also read this article http://hangar.runway7.net/javascript/guide from the same author.

You can pass additional parameters (comma separated) to call. The first param is considered as the object and the other parameters as parameters.

You can pass first parameter and additional parameters (in the form of array) to call. The first param is considered as the object and the array of parameters is taken in as additional parameters.

You can pass first parameters and additional parameters to bind. It creates a new function with the first param as the object and the rest of the params as params.

call - for comma separated params
array - for array form of params
bind - a new function

Read more: https://codeplanet.io/javascript-apply-vs-call-vs-bind/


JavaScript Currying

Came across this site that explains JavaScript Currying in simple words. Good reading:)

https://www.sitepoint.com/currying-in-functional-javascript/

Wednesday, October 19, 2016

What is "export default" in JavaScript?

ES6 is the first time that JavaScript has built-in modules. ES6 modules are stored in files.

The "export" statement is used to export functions, objects or primitives from a given module(or file).

There are two types of export available:

  • Named export - useful to export several values from a given file.
  • Default export - there can only be a single default export from a given file. 
If a module defines a default export, then you can import the default export by omitting the curly braces.

Read more:

Friday, October 7, 2016

ReactJS

What is ReactJS?


Following is the answer that I found when searched the above question on Google:

"React is a JavaScript library for creating user interfaces by Facebook and Instagram. Many people choose to think of React as the V in MVC. We built React to solve one problem: building large applications with data that changes over time."

Links to read more about ReactJS:




https://egghead.io/courses/getting-started-with-redux

https://css-tricks.com/learning-react-router/

How to access ReactJS libraries?

  • Accessing ReactJS library from cdn in the html file is one way. (Refer: https://www.kirupa.com/react/creating_single_page_app_react_using_react_router.htm)
  • <!DOCTYPE html>
    <html> 
    <head>
    <title>Creating React Component with React.createClass</title>
    <script src="https://unpkg.com/react@15.3.2/dist/react.js"></script>
    <script src="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
    </head>
    
    <body>
     <div id="app"></div>
     <script type="text/babel">
     var destination = document.getElementById("app");
    
     var App = React.createClass({
       render: function() {
         return (
           <div>
             <h1>Welcome World!!</h1>
           </div>
         )
       }
     });
    
     ReactDOM.render(
       <div>
         <App/>
       </div>, 
       destination
     ); 
     </script>
    </body>
    
    </html>
  • Accessing ReactJS related modules from npm and bundle them and provide them to the html file is another way. (Refer: https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm)
How to create ReactJS components?

There are two ways to create the ReactJS components.
  • Using the traditional way: React.createClass
  • Using the ES6 way: extends React.Component

Setting up Sublime-Text for React JSX development:

http://www.nitinh.com/2015/02/setting-sublime-text-react-jsx-development/

Sunday, September 18, 2016

Node basics

How to parse command line arguments in nodejs?

>node test.js hi hello cool

test,js
var cmdArgs = process.argv.slice(2);
console.log(cmdArgs); //prints ["hi","hello","cool"]

How to write a reusable module and how to import it in test.js?

myreusablemodule.js
module.exports = {
      sayHello : function(){
           console.log("Hello, how u doing?");
     }
};

test.js
var rModule = require("./myreusablemodule"); //returns whatever is assigned to module.exports
console.log(rModule.sayHello());

>node test.js

Explain about event driven programming in nodejs?

In an event driven programming, there is a main loop that listens for events, and then triggers a callback function when one of these events is detected.
Read more here: https://www.tutorialspoint.com/nodejs/nodejs_event_loop.htm

Give an example of event driven programming in nodejs?

All you need to remember is on and emit.

test.js
var events = require("events");
var eventsEmitter = new events.EventEmitter();
var mycustomeventassocfunction = function(){
      console.log("i am the response from mycustomeventassocfunction");
};
eventsEmitter.on("mycustomevent",mycustomeventassocfunction);

eventsEmitter.emit("mycustomevent");

>node test.js

How does the async functions work in nodejs?

Events and callbacks help nodejs to support concurrency.
database.query('something', function(err, result) {
  if (err) handle(err);
  doSomething(result);
});
The async function query takes callback function as the last parameter and the callback function takes err as the first parameter.
Read more here: https://www.tutorialspoint.com/nodejs/nodejs_event_loop.htm

What are the global objects in nodejs?

You don't have to require/include the global objects in nodejs programs. For example, console, process, __filename, __dirname, etc.

Read more here: https://www.tutorialspoint.com/nodejs/nodejs_global_objects.htm

test.js
console.log(__filename);

>node test.js

Friday, September 9, 2016

Cross-Origin Resource Sharing (CORS)


  • Say, web site a.com has some data that b.com site wants to access.
  • Web browser's same origin policy won't allow that happen.
  • If a.com supports CORS requests (that are made by sites like b.com) by adding a few special response headers, b.com can access the data.
  • CORS (Cross-Origin Resource Sharing) is a W3C spec that allows cross-browser communication from the browser. By building on top of the XMLHttpRequest object, CORS allows developers to work with the same idioms as same-domain requests. Read more in this html5rocks tutorial by Monsur Hossain!

Tuesday, August 30, 2016

Learn SQL queries on Oracle database

  • Go to http://sqltest.net/
  • Select Oracle 11g from the drop down on the right side of the black navigation bar.
  • Use these practice queries from this site.

Friday, August 19, 2016

Statistical Analysis System (SAS)


  • What does SAS stands for?
    • Statistical Analysis System
  • Who was the founder of SAS?
    • Jim Goodnight
  • How long SAS been around?
    • Around 30 years
  • What do you do with SAS software?
    • Gather, massage and manage the data, analyze the data, generate reports based on data.
  • What is the SAS software comprised of?
    • SAS Server to collect and save data, SAS Applications such as Enterprise Guide, SAS add-on for Microsoft Office, SAS Web Report Guide.
  • What are the SAS data access products?
    • SAS/ACCESS products that run on SAS Server.
  • Where can you download SAS software at free of cost?
  • What is a task in Enterprise Guide?
    • Tasks are the built-in wizards of Enterprise Guide.
  • Name couple of Enterprise Guide tasks?
    • Query Builder, Graphs, Reports, etc.
  • Why do you use charts in SAS?
    • To summarize the data.
  • Explain the basic mathematical terms mean, median, mode, range and give an example?
    • Mean is the average of all given numbers
    • Median is the middle number in the given numbers when arranged from smallest to largest
    • Mode is the number that appears the most in the given numbers
    • Range is the difference between the largest and smallest numbers in the given numbers
    • Let's find mean, median, mode, range of the given numbers 10, 18, 11, 11, 15
    • Mean: (10+18+11+11+15) / 5 = 13
    • Median: put the numbers in order: 10,11,11,15,18...and pick the middle number, 11
    • Mode: most appeared number is 11
    • Range: 18 (largest number) - 10 (smallest number) = 8
  • List some of the top pharmaceutical companies in USA?
  • Name some of the top clinical research organizations (CRO)?
    • Qunitiles, Covance, Parexel, Icon, INC, PPD, inVentiv, PRA, CRLI, WuXi
  • Name some of the top health foundations?
    • Bill & Melinda Gates Foundation, Robert Wood Johnson Foundation, Kresge Foundation, Nemours, W.K.Kellogg Foundation, Kaiser Parmanente.
  • Where can I learn more about Clinical Studies?
  • What are the clinical trial phases?
  • What is an IND Application?
    • IND stands for Investigational New Drug.
    • The drug sponsors file IND application to get the exemption from FDA to ship the experimental drug across the state lines (the intention is to use the drug in animal studies and human clinical trials). 
    • IND Application should have information in 3 broad areas: Animal Pharmacology and toxicity studies, Manufacturing information, Clinical Protocols and investigator information.
    • There are 3 IND types: Investigator IND, Emergency use IND, Treatment IND
    • Once the IND is submitted, the sponsor must wait 30 calendar days before initiating any clinical trials.
    • Read more at fda.gov
  • What is NDA Application?
    • NDA stands for New Drug Application.
    • The drug sponsors file NDA application with FDA to get the approval to sell the drug.
    • The data collected from IND becomes part of NDA.
    • Read more at fda.gov
  • What is the format of a proc step? (See for more details: http://www2.sas.com/proceedings/sugi29/256-29.pdf)

Thursday, July 28, 2016

Content Security Policy

What is Content Security Policy?


CSP defines the Content-Security-Policy HTTP header that allows you to create a whitelist of sources of trusted content, and instructs the browser to only execute or render resources from those sources. Even if an attacker can find a hole through which to inject script, the script won’t match the whitelist, and therefore won’t be executed.

Read more: http://www.html5rocks.com/en/tutorials/security/content-security-policy/

Saturday, April 16, 2016

Web workers


  • HTML5 introduced web workers to support JavaScript multi-threading.
  • Web workers run on a separate thread in parallel to browser's UI thread.
  • Web workers can only access limited objects such as functions, and objects like strings, numbers, Date, Array, XMLHttpRequest, etc.
  • The worker and the parent page communicate using messaging. Each can add a listener to the onmessage() event to receive messages from the other.
  • Read more from this article written by Robert Gravelle and from this article written by Eric Bidelman.

Give it five minutes

Did you learn anything today? You might have learnt something that is good or bad, useful or useless, or learnt some stuff that could help you in your day to day job. Today I came across this wonderful article written by Jason Fried who talked about giving some time to think about something instead of immediately pushing it back. Read this article to understand what that means!

Sunday, April 3, 2016

HTML5 template tag. - And also the script tag with type as text/template.

MDN Definition of template tag says The HTML template tag <template> is a mechanism for holding client-side content that is not to be rendered when a page is loaded but subsequently be instantiated during runtime using JavaScript.

Read from this blog, http://www.html5rocks.com/en/tutorials/webcomponents/template/, on how to use and access the template tag contents.

Also the script tag with type as text/template works the same way:

By setting the type to "text/template", it's not a script that the browser can understand, and so the browser will simply ignore it. This allows you to put anything in there, which can then be extracted later and used by a templating library to generate HTML snippets.

<!doctype html>
<head>
<head>
<script>
window.onload=function(){
    document.getElementById('targetDiv').innerHTML = document.getElementById('hiddenTemplate').textContent;
};
</script>
</head>
<body>
<script id="hiddenTemplate" type="text/template">
    Type something: <input type="text" id="mailbox" />
    <button id="postMsgBtn">Send this message to main window</button>
    <div id="msg"></div>
</script>

<div id="targetDiv"></div>
</body>
</html>

HTML5 window.postMessage - communication between windows/frames hosted on different domains

window.postMessage allows safe communication between windows/frames hosted on different domains.

Concept is simple: Post a message from one window (origin) or another window (target) and check for any message received  in the target window.

An example:

<!doctype html>
<html>
<head>

<script>
window.onload=function(){

    var iframeNode = document.getElementById("iframe");
    var iframe = iframeNode.contentWindow;
    iframe.document.body.innerHTML = document.getElementById('hiddenTemplate').textContent;

    var parentButtonNode = document.getElementById("postMsgBtn");
    var childButtonNode = iframe.document.getElementById("postMsgBtn");
    
    //  Post a message from main window to the iframe
    parentButtonNode.addEventListener('click',function(){
        iframe.postMessage(document.getElementById("mailbox").value, "http://localhost");       
    });

    //  Post a message from iframe to the main window
    childButtonNode.addEventListener('click',function(){
        iframe.parent.postMessage(iframe.document.getElementById("mailbox").value, "http://localhost");       
    });

    //  Check in main window if you received a message from iframe
    window.addEventListener('message', function(event) {
        if (event.origin !== "http://localhost"){
            return;
        }
        document.getElementById("msg").innerHTML = "Received this from iframe<span style='color:red;'>: " + event.data + "</span>";
    });

    //  Check in iframe if you received a message from main window
    iframe.addEventListener('message', function(event) {
        if (event.origin !== "http://localhost"){
            return;
        }
        var msgNode = iframe.document.getElementById("msg");
        msgNode.innerHTML = "Received this from main window<span style='color:red;'>: " + event.data + "</span>";
    });
}
</script>
</head>
<body>

<!-- hidden HTML template that will be used inside iframe -->
<script id="hiddenTemplate" type="text/template">
    Type something: <input type="text" id="mailbox" />
    <button id="postMsgBtn">Send this message to main window</button>
    <div id="msg"></div>
</script>

<!-- iframe and it's content -->
<iframe id="iframe" src="about:blank" width="600px"></iframe>

<!-- Main page content -->
Type something: <input type="text" id="mailbox" />
<button id="postMsgBtn">Send this message to iframe</button>
<div id="msg"></div>

</body>
</html>

Sunday, March 13, 2016

Dojo define() Vs require()

This is the simplest explanation that I come across that explained the differences between dojo define() and require(){

http://g00glen00b.be/dojo-require-vs-define/

Tuesday, March 1, 2016

NodeJS for Beginners

I come across the following site where it was explained in simple about node, node custom modules, making database connection from a node module, etc. A must read...

http://code.tutsplus.com/tutorials/nodejs-for-beginners--net-26314

Monday, February 29, 2016

NodeJS and PhoneGap

Phonegap is a client-side solution only with JavaScript/CSS/HTML running on the browser-app of the phone. The JavaScript Phonegap API talks to the native phone interface and browser interface which gives you options to work natively and as a normal web page would with enhanced permissions. Node.js would only serve you as a data connection for JSON or whatever else you would need to pull/push with a network call.

Reference: http://stackoverflow.com/questions/14513029/phonegap-with-node-js

Wednesday, February 3, 2016

CSS: Elements do not expand to contain floated children by default

Elements do not expand to contain floated children by default.

There are a number of workarounds, such as floating the parent, using a clearfix or adding overflow: hidden to the parent.

Saturday, January 30, 2016

Fetch multiple rows using PHP, MySQL

<?php    

      $dbc = mysqli_connect("localhost""my_user""my_password""my_database")  or die ("Error connecting to the mysql server. ");

      $query = "select * from my_table";

      $result = mysqli_query($dbc, $query)or die ("Could not connect to mysql server. ");
             
        $myArray = array();
    
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
             $myArray[] = $row;
        }

        $result->free(); 
    
        mysqli_close($dbc);

        //TEST TO SEE THE RESULT OF THE ARRAY 
        echo '<pre>';
             print_r($myArray);
        echo '</pre>';


?>