Monday, September 28, 2020

Time Management and Productivity

As someone who is data and productivity fanatic, this post is going to be about breaking the schedule, tracking the data while there is a schedule and there is not a schedule and how to measure more accurate metrics. 



Friday, July 31, 2020

(College Education - 2) What if you get 100K USD job after a 200$ course. Will you pay for college then?

If you have not read my previous article on college education, you can find the link over here

Wednesday, July 8, 2020

Why this pandemic is an ultimate test.


Humans have survived on the hope of a better future. The now is pretty irrelevant as long as there is the promise of a better future. We have led ourselves to narrate a sippy dream filled with brighter future of neon lights and disposable human connections. Nobody expected to be in a home lockdown, irrespective of the fact that's what we would have been doing anyway, the imposition of such comes as a big blow. Something more precious than the present has been taken away from us, the promise of a better future. 

The psychological impact of it is insanely high. We have to deal with someone, we have to live with someone we rarely have an honest conversation with, ourselves. This pandemic is also a long coming for so many issues that plagued society, we are looking at improved conversations on the division of labour between genders, mental health, social media addiction, unimpactful education system and so on. It is indeed an extraordinary situation where everyone seems to be stuck together (and yet alone) in an elevator that sometimes goes up, sometimes down, but the doors don’t open and the help button is broken.

And that is why this pandemic is an ultimate test for homo sapiens. 
We need to create reasons to find hope, because I am pretty sure this won't go on more than 3-4 months from now on. The vaccine would be prepared and when it does we should be ready to do what we always dreamt of. 

Tuesday, June 9, 2020

GraphQL , ReactJS and Apollo Client

We will build a client-sided GraphQL application which will combine React with GraphQL. The application would allow us to gather facebook profile information

The following tutorial will be split into four sections.

  • What is GraphQL and how is it different from REST API.
  • What is Reactjs and Why should you use it?
  • Creating a GraphQL backend in nodejs and express.
  • Connecting Apollo Client to a react application

What is GraphQL and how is it different from REST API?

One might ask themselves that they already understand the REST APIs very well and if there is a true need of GraphQL at all. GraphQL is based on objects instead of strings (comparing to SQL) and thus reduces complexity of the application.

All the requests in GraphQL are handled by a single a end-point /graphql. Let that sink in for a while.

Why does this matter? The actual transmission of requests and data is abstracted away. We no longer have to worry about things like response codes and planning out our urls like
/articles/id/comments/user_id/comment_id/delete.
In the HTTP API structure, we had to create 4 API to interact with our single object in model which were largely,

  • post
  • get
  • delete
  • put

whereas GraphQL would have handler functions which would handle things for us.

To summarize it we have following advantages of GraphQL.
GraphQL is declarative: Query responses are decided by the client rather than the server. A GraphQL query returns exactly what a client asks for and no more.

GraphQL is compositional: A GraphQL query itself is a hierarchical set of fields. The query is shaped just like the data it returns. It is a natural way for product engineers to describe data requirements.

GraphQL is strongly-typed: A GraphQL query can be ensured to be valid within a GraphQL type system at development time allowing the server to make guarantees about the response. This makes it easier to build high-quality client tools

GraphQL fits in very well with abstraction based concept on which facebook devoloper tools function. The idea that abstraction reduces complexity is common across React, GraphQL and other devoloper tools that facebook has created and thus it workds seamlessly with ReactJS.

What is Reactjs and Why should you use it with GraphQL?

The number of front-end libraries built on top javascript has clearly surpassed a guessable number. This has led it to be the butt of many jokes. There is a popular drinking joke amongst developers where a person names a noun and if there exists a js library with such a name, you are supposed to drink

A new library called ReactJS somehow has emerged as the uncrowned champion amidst this bubble. It has gained massive popularity amongst management and developers alike. The best part about react js is that to get started you only need a basic understanding of HTML and Javascript. Not only is it easy to learn but also easy to migrate as it is not a framework but a library with small compatibility layers In this article, we will talk about why you should migrate to ReactJS and list few of the tech companies that have done the same.

  1. SuperSonic Load
    ReactJs uses Virtual Dynamic Object Model (V-DOM) which is built with a diff algorithm (A tree of elements hierarchy is created, it is then calculated as to what is the fastest way to change the tree in order to get desired results). The basic idea behind V-DOM is that the changes are made in virtual DOM with pure javascript as compared to live DOM. Only the minimal changes that are needed to be made to page happen. So both the data bindings and changes to page content is minimalistic.

  2. Easy to Build
    As mentioned in the first paragraph, developers are already familiar with Javascript so it is easy for them to get hands-on coding with ReactJS. This combined with the fact that the complete ReactJS framework is built on components thus making it easier to do A/B testing. For example, we can have an A/B test that compares 9 different design variations in the UI, which could mean maintaining code for 10 views for the duration of the test. This modular aspect makes it easy to test and reuse the same components in multiple places across devices.

  3. Security
    With technologies coming and going so haphazardly, the need for a stable technology is what organizations are looking for. And, ReactJS is just that, since it is backed by big names like Facebook, Instagram and millions of developers globally. Even, with peer competition increasing, ReactJS has been able to sustain its popularity level and in fact, has been soaring high still. Hence, developers find security and stability in opting for React.

  4. Great Runtime Performance
    To build the best visually-rich user experience for the webapp, efficient UI rendering is critical. While there are fewer hardware constraints on desktops/laptops (compared to other devices), expensive operations can still compromise UI responsiveness. In particular, DOM manipulations that result in reflows and repaints are especially detrimental to user experience. ReactJS comes with great runtime experience for the user.

  5. Isomorphic Javascript
    React enables developers to build JavaScript UI code that can be executed in both server (e.g. Node.js) and client contexts. React allows the basic back-end to load whereas the client context can be loaded over time without the live DOM, thus reducing the loading time by a huge margin. Furthermore, the UI code written using the React library that is responsible for generating the markup could be shared with the client to handle cases where re-rendering was necessary.

Creating a GraphQL backend in nodejs and express.

We will first create a node directory that contains our backend. We will initialize using the command $ npm init in our terminal and initialize the npm repository. Furthermore create a new server.js file in the project directory. That will be the file where the code required to implement the Node.js GraphQL server will be inserted in the next section:

$ touch server.js

Finally make sure that NPM packages graphql, express and express-graphql are added to the project:

$ npm install graphql express express-graphql --save

Having installed these packages successfully we’re now ready to implement a first GraphQL server.

Then we will create our server.js file and copy the following code.

var express = require('express');
var express_graphql = require('express-graphql');
var {buildSchema} = require('graphql');
// we require all dependencies
// GraphQL Schema
// We are passing the GraphQL Interface Definition Language which is used to define the schema 
// It defines how the schema of our object is going to look like. 
var schema = buildSchema(`
    type Query {
        message: String
    }
`);

// Root resolver
// Root resolver has mapping to actions to functions. This is also called as handler functions.
var root = {
    message: () => 'Hello Wold!'
};

// Create an expres server and a GraphQL endpoint, notice that there is only one end point as we stated before
var app = express();
app.use('/graphql', express_graphql({
    schema: schema,
    rootValue: root,
    graphiql: true
}));

app.listen(4000, () => console.log('Express GraphQL Server Now Running On localhost:4000/graphql'));

The code has been heavily commented so that you can easily understand what each and every line means. There are two main components here to focus on

  • GraphQL Schema
  • Root Resolver

GraphQL schema
It is used to describe the complete APIs type system. It includes the complete set of data and defines how a client can access that data. Each time the client makes an API call, the call is validated against the schema. Only if the validation is successful the action is executed. Otherwise an error is returned.

Root Resolver
Resolver contains the mapping of actions to functions. In our example from above the root resolver contains only one action: message. To keep things easy the assigned functions just returns the string Hello World!. Later on you’ll learn how to include multiple actions and assign different resolver functions.

At the end of code we create and express end-point where these queries can be consumed.

Next we will move on to our actual code and a more sophisticated example. You can create a new file and and copy paste the following code in it.

var express = require('express');
var express_graphql = require('express-graphql');
var {buildSchema} = require('graphql');

// GraphQL Schema
var schema = buildSchema(`
    type Query {
        course(id: Int!): Course
        courses(topic: String): [Course]
    }
    type Mutation {
        updateCourseTopic(id: Int!, topic: String!): Course
    }
    type Course {
        id: Int
        title: String
        author: String
        description: String
        topic: String
        url: String
    }
`);

var coursesData = [
    {
        id: 1,
        title: 'The Complete Node.js Developer Course',
        author: 'Andrew Mead, Rob Percival',
        description: 'Learn Node.js by building real-world applications with Node, Express, MongoDB, Mocha, and more!',
        topic: 'Node.js',
        url: 'https://codingthesmartway.com/courses/nodejs/'
    },
    {
        id: 2,
        title: 'Node.js, Express & MongoDB Dev to Deployment',
        author: 'Brad Traversy',
        description: 'Learn by example building & deploying real-world Node.js applications from absolute scratch',
        topic: 'Node.js',
        url: 'https://codingthesmartway.com/courses/nodejs-express-mongodb/'
    },
    {
        id: 3,
        title: 'JavaScript: Understanding The Weird Parts',
        author: 'Anthony Alicea',
        description: 'An advanced JavaScript course for everyone! Scope, closures, prototypes, this, build your own framework, and more.',
        topic: 'JavaScript',
        url: 'https://codingthesmartway.com/courses/understand-javascript/'
    }
]

var getCourse = function(args) {
    var id = args.id;
    return coursesData.filter(course => {
        return course.id == id;
    })[0];
}

var getCourses = function(args) {
    if (args.topic) {
        var topic = args.topic;
        return coursesData.filter(course => course.topic === topic);
    } else {
        return coursesData;
    }
}

var updateCourseTopic = function({id, topic}) {
    coursesData.map(course => {
        if (course.id === id) {
            course.topic = topic;
            return course;
        }
    });
    return coursesData.filter(course => course.id === id)[0];
}

// Root resolver
var root = {
    course: getCourse,
    courses: getCourses,
    updateCourseTopic: updateCourseTopic
};

// Create an expres server and a GraphQL endpoint
var app = express();
app.use('/graphql', express_graphql({
    schema: schema,
    rootValue: root,
    graphiql: true
}));

app.listen(4000, () => console.log('Express GraphQL Server Now Running On localhost:4000/graphql'));

We write GraphQL query to fetch us the required results. You can explore this using the http://localhost:4000/graphql server. This code helps you to get a course, get courses and update a course Topic.

Connecting Apollo Client to a react application

We use the create-react-app to get us started with our project.

$ npx create-react-app react-graphql-frontend 
$ cd react-graphql  
$ npm start

The following packages needs to be installed:

  • apollo-boost: Package containing everything you need to set up Apollo Client
  • react-apollo: View layer integration for React
  • graphql-tag: Necessary for parsing your GraphQL queries
  • graphql: Also parses your GraphQL queries

The installation of these dependencies can be done by using the following NPM command:

$ npm install apollo-boost react-apollo graphql-tag graphql

The main entry point of the React application can be found in index.js. The code contained in this file is making sure that App component is rendered out to the DOM element with ID root.Here is how the file should look.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';


ReactDOM.render(<App />, document.getElementById('root'));

App.js

The main logic of our code is present in App.js. We need to do the following tasks.

  • Creating An Instance Of ApolloClient
  • Connecting ApolloClient To Your React App

Creating An Instance of ApolloClient
First ApolloClient is imported from the apollo-boost library. A new instance of ApolloClient is created and stored in client. To create a new instance of ApolloClient you need to pass a configuration object to the constructor. This object must contain the uri property. The value of this property must be replaced which the URI of the GraphQL endpoint which should be accessed.

import ApolloClient from "apollo-boost";
const client = new ApolloClient({  
  uri: "[Insert URI of GraphQL endpoint]"  
});

Connecting ApolloClient To your react App
Having established a connection to the GraphQL endpoint by using ApolloClient we now need to connect the instance of ApolloClient to the React app. To do so, please make sure to add the following lines of code in App.js:

import { ApolloProvider } from "react-apollo";...const App = () => (  
 <ApolloProvider client={client}>
    <div className="container">
      <nav className="navbar navbar-dark bg-primary">
        <a className="navbar-brand" href="#">React and GraphQL - Sample Application</a>
      </nav>
      <div>
        <Courses />
      </div>
    </div>
  </ApolloProvider>
);

Fist ApolloProvide is imported from the react-apollo library. The <ApolloProvider> element is then used in the component’s JSX code and is containing the template code which is used to render the component. This is what the final version of App.js would look like.

App.js

import React, { Component } from 'react';
import './App.css';
import Courses from './Courses';

import ApolloClient from "apollo-boost";
import { ApolloProvider } from "react-apollo";


const client = new ApolloClient({
  uri: "http://localhost:4000/graphql"
});


const App = () => (
  <ApolloProvider client={client}>
    <div className="container">
      <nav className="navbar navbar-dark bg-primary">
        <a className="navbar-brand" href="#">React and GraphQL - Sample Application</a>
      </nav>
      <div>
        <Courses />
      </div>
    </div>
  </ApolloProvider>
);
export default App;

Course.js

So far the output of courses is done within the Courses component. In the next step we’re going to introduce a new component to our project: Course. This component should then contain the code which is needed to output a single course. Once this component is available in can be used in Courses component.

First let’s add a new file Course.js to the project and insert the following lines of code:.

import React from 'react';
const Course = (props) => (
    <div className="card" style={{'width': '100%', 'marginTop': '10px'}}>
        <div className="card-body">
        <h5 className="card-title">{props.course.title}</h5>
        <h6 className="card-subtitle mb-2 text-muted">by {props.course.author}</h6>
        <p className="card-text">{props.course.description}</p>
        <a href={props.course.url} className="card-link">Go to course ...</a>
        </div>
    </div>
);
export default Course;

The implementation of this component is quite simple. The current course is handed over to Course component as a property and is available via props.course.

courses.js

Next we create a new courses component and copy paste the following in it.
courses.js

import React from 'react';
import { Query } from "react-apollo";
import Course from './Course';
import gql from "graphql-tag";


// The Query component makes it extremely easy to embed the GraphQL query directly in the JSX code of the component. 
// Furthermore the Query component contains a callback method which is invoked once the GraphQL query is executed.

const Courses = () => (
  <Query
    query={gql`
      {
        allCourses {
          id
          title
          author
          description
          topic
          url
        }
      }
    `}
  >
    {({ loading, error, data }) => {
      if (loading) return <p>Loading...</p>;
      if (error) return <p>Error :(</p>;
    
        return data.allCourses.map((currentCourse) => (
            <Course course={currentCourse} />
        ));
    }}
  </Query>
);

export default Courses;

This is the implementation of the Courses component. To retrieve data from the GraphQL endpoint this component makes use of another component from the React Apollo library: Query. The Query component makes it extremely easy to embed the GraphQL query directly in the JSX code of the component. Furthermore the Query component contains a callback method which is invoked once the GraphQL query is executed.

Here we’re using the JavaScript map method to generate the HTML output for every single course record which is available in data.allCourse.

Conclusion

Hey! All this is cool but how does one decide which tech stack to use. The question has been answered several times and by several ingenious folks and there is no correct answer. It truly depends on use-case, complexity and scalability requirements for the application. Often at time you would have to evolve and change multiple things for your application. It is important to note that these stacks work perfectly well in tandem with each other. So, you can very well have Rails backend serving you a GraphQL along with React front-end. We know Rails is very good at handling back-end logic and we also know the React’s ability to handle front-end which gives us an amazing combination.

Thursday, May 21, 2020

Your First SPA in ReactJS, NodeJS

Your First SPA in ReactJs, NodeJS

Today we are going to build a simple blog application that will help you get started with ReactJS with back-end built over NodeJS The complete tutorial has been split into SIX IMPORTANT steps.

  1. Installing the required tools

  2. Understanding NodeJS structure (Back-end of your application)

  3. Coding Your APIs

  4. Understanding ReactJS structure (Front-end of your application)

  5. Designing and Coding your Front-end

  6. Grab a good drink and pat yourself on the back for doing an excellent job.

Installing the required tools


Let’s get our tools installed and start the fire going to get us started with building our Blog Application. We will use ReactJS, NodeJS, Express and MongoDB.

  • Node.js: Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js brings JavaScript to the server

  • MongoDB: A document-based open source database

  • Express: A Fast, unopinionated, minimalist web framework for Node.js

  • React: A JavaScript front-end library for building user interfaces

Let’s install them on a Debian based system. You can ignore this section if you already have them installed. Fire up the terminal by hitting the keys Cltr+Altr+T and do the following.

Installing NodeJs and NPM

$ wget https://nodejs.org/dist/v6.9.2/node-v6.9.2-linux-x64.tar.gz

# tar -xf node-v6.9.2-linux-x64.tar.gz --directory /usr/local --strip-components 1

Next, we will install express, react, cors and mongoose.


$ npm install express body-parser cors mongoose react nodemon

A long-form version of the same is to use npm install express/react --save but the shorthand version comes in handy very often.

Now, we install MongoDB. You can also cloud solution called as mlab.com but for this tutorial, we will use the one on your system instead.


$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927

$ sudo bash -c 'echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.0 multiverse" > /etc/apt/sources.list.d/mongodb-org-4.0.list'

$ sudo apt-get update

$ sudo apt-get install -y mongodb-org

If you have some issues with mongodb installation,check this out. It has very succinct guide on how to setup your MongoDB environment.

Understanding NodeJS structure (Back-end of your application)

In this section we will deal with only two files. One that defines our model and other that helps us with setting up our HTTP API endpoints.

  • models/modelname.js
    This would have the schema of the database. In our case we are going using mongoose database adapter to connect with our MongoDB
  • /server.js
    This would alllow back-end to function.

The back-end will comprise HTTP endpoints to cover the following use cases:

  • Retrieve the complete list of available blog articles by sending an HTTP GET request

  • Retrieve a specific blog article by sending HTTP GET request and provide the specific blogID in addition

  • Create a new blog article in the database by sending an HTTP POST request

  • Update an article in the database by sending an HTTP POST request

Let’s understand how NodeJS along with express communicates to the database (mongoose). We will setup the app.js in our project directory and copy-paste the following code. The code is commented on various sections to help you understand with each and every line of it. Make sure you have setup MongoDB database correctly while implementing this code. You would need to change database URL in order to make this function correctly.

const express = require('express');  
// using express library

const app = express();  
// this creates an instance of express module, enabling the feature
// module.exports. 

const bodyParser = require('body-parser');
// this enables us to parse JSON
  
const cors = require('cors');  
//Cross Origin Resource Sharing, it allows/denies/sets rules for cross domain requests in the application. 

const mongoose = require('mongoose'); 
 // MongoDB adapter for NodeJS
 
const PORT = 4000;
// Where the application would run on Mongoose. 

app.use(cors());  

app.use(bodyParser.json());

mongoose.connect('mongodb://127.0.0.1:27017/', { useNewUrlParser: true });  
// you need to specify database URL. Make sure this is correctly set up with
// database you are using. 

const connection = mongoose.connection;connection.once('open', function() {  
    console.log("MongoDB database connection established successfully");  
})

app.listen(PORT, function() {  
    console.log("Server is running on Port: " + PORT);  
});

Next we will run nodemon server inside the directory to make sure if the code is functional. The express server would be live on http://localhost:4000.

Coding our APIs


As we have already mentioned before the APIs that we are going to use. Now let us build the API logic around our application. This would allow the API call made to make changes to our database.

Our database would only have a single doucment that will allow us to store the blog article. We would need to create the Mongoose Schema for that document.

models/article.js

const mongoose = require('mongoose');  
const Schema = mongoose.Schema;
let Article = new Schema({  
    content: {  
        type: String  
    }, 
    author: {  
        type: String  
    }  
});
module.exports = mongoose.model('Article', Article);

Next we will make endpoints in order to update the document in the schema. In order to do so we need a express router. The router will be added as a middleware and will take control of request starting with path /articles:

const articleRoutes = express.Router();

Now we will make an end-point that delivers us all the articles from our database.

articleRoutes.route('/articles').get(function(req, res) {  
    Article.find(function(err, articles) {  
    if (err) {  
		console.log(err);  
    } 
    else
     {  
	    res.json(articles);  
	  }  
  });  
});

The function which is passed into the call of the method get is used to handle incoming HTTP GET request on the /articles/ URL path. In this case we’re calling Article.find to retrieve a list of all articles from the MongoDB database. Again the call of the find methods takes one argument: a callback function which is executed once the result is available. Here we’re making sure that the results (available in todos) are added in JSON format to the response body by calling res.json(articles).

Now we will create an API which will allow us to get a specific article based on id passed on to it.
The url would look something like this /article/:id_. Here :id the path extension is used to retrieve a article item from our database. The implementation logic is straight forward:

articleRoutes.route('/article/:id').get(function(req, res) {  
    let id = req.params.id;  
    Article.findById(id, function(err, art) {  
	    res.json(art);  
    });  
});

Next, let’s add the route which is needed to be able to add new articles by sending a HTTP post request (/article/new):

articleRoutes.route('/article/new').post(function(req, res) {  
    let art = new Article(req.body);  
    art.save()  
	.then(art => {  
	    res.status(200).json({'art': 'article created successfully'});  
    })  
    .catch(err => {  
	    res.status(400).send('creating a new article failed');  
    });  
});

The new article is part the the HTTP POST request body, so that we’re able to access it via req.body and therewith create a new instance of Article in our Mongoose Database. This new item is then saved to the database by calling the save method.

Now we come to our final API which would allow us to update the blog article.

articleRoutes.route('/article/update/:id').post(function(req, res) {  
    Article.findById(req.params.id, function(err, art) {  
        if (!art)  
            res.status(404).send("data is not found");  
        else  
            art.content = req.body.content;  
            art.author = req.body.author;  
        art.save().then(todo => {  
                res.json('Article updated!');  
            })  
            .catch(err => {  
                res.status(400).send("Update not possible");  
            });  
    });  
}); 

Here is the complete source code for the nodejs backend file server.js and you can also check out the mongoose schema mentioned above over here.

Understanding ReactJS structure

Before we start exploring the structure let’s setup our application by creating the react app. You can do this in multiple ways but I suggest you use the trustworthy module ‘create-react-app’. It will help you get up running quickly.

$ npm i -g create-react-app
$ create-react-app blog_spa
$ cd blog_spa

We would also setup react-router-dom. This would allow us to change the URL without sending a request to the server. Axios would allow us to send and recieve HTTP requests.

$ npm i react-router-dom axios --save

There are two main folders that we are largely going to interact with while our development of reactjs SPA.

  • src
  • public

Now we will delete everything that’s present in src and pulic folder. You can do it from GUI or from terminal, it doesn’t make a whole lot of difference.

Now we will create the main page which will work as the skeleton of your application. [aka MasterPage if you are migrating from ASP.NET] React allows us to choose which components to show and which to hide on the basis of url. This is done with the help of HashRouter , NavLink and Route from react-router-dom library. We also import the content pages from different components that we want.

src/main.js

import React, { Component } from "react";
import {
  Route,
  NavLink,
  HashRouter
} from "react-router-dom";
import allPosts from "./allPosts";
import newArticle from "./newArticle";
import article from "./article";

class Main extends Component {
  render() {
    return (
      <HashRouter>
        <div>
          <h1>Blog SPA</h1>
          <ul className="header">
            <li><NavLink to="/">All Articles</NavLink></li>
            <li><NavLink to="/new">New Article</NavLink></li>
          </ul>
          <div className="content">
           <Route exact path="/" component={allPosts}/>
          <Route path="/new" component={newArticle}/>
          <Route path="/article/:id" component={article}/>
/* the last route is added so that we can display indivdual article on load. We are not consuming any api over here */
          </div>
        </div>
      </HashRouter>
    );
  }
}
 
export default Main;

src/index.js

We need to load the main file on every page of our application, so we add this basic code.

import React from "react";
import ReactDOM from "react-dom";
import Main from "./main";
 
ReactDOM.render(
  <Main/>, 
  document.getElementById("root")
);

Coding our Front-End


Now we come towards the final stage of our tutorial. We need create three pages that will allow us to connect with our node.js backend application. We will use axios, so that will allow us to communicate with our backend APIs. Notice how we pass variables across the render section and our function componentDidMount(). We are using a GET request to retrieve all the articles from our back-end.

src/allPosts.js

import React, { Component } from "react";
import {
  Route,
  NavLink,
  HashRouter
} from "react-router-dom";import axios from 'axios';



class allPosts extends Component {
  state = {
    articles: []
  }

  componentDidMount() {
    axios.get(`http://localhost:4000/articles`)
      .then(res => {
        const a = res.data;
        console.log(a);
        this.setState({ articles: a });
      })
  } 
  render() {
    return (
              <HashRouter>

      <div>
           {this.state.articles.map(art => <div> <h2> <NavLink to={`article/${art._id}`}>Blog Post by {art.author}</NavLink> </h2> {art.content}</div>)}
                     <div className="content">

    </div>       
      </div>
          </HashRouter>

    );
  }
}
 
export default allPosts;

src/newArticle.js

Now we need to send a post-request which will allow creating of a new article. To make it easier, we are passing the author as string instead of user input.

import React, { Component } from "react";
import axios from 'axios';

 
class newArticle extends Component {
  state = {
    content: '',
  }

  handleChange = event => {
   // console.log(event.target.value)
    this.setState({ content: event.target.value });
  }

  handleSubmit = event => {
    event.preventDefault();

    const article = {
      content: this.state.content,
      author: 'vaibhavgeek'
    };

    axios.post(`http://localhost:4000/article/new`,  article )
      .then(res => {
        //console.log(res);
        console.log(res.data);
        console.log(event);
        this.setState({ content: "" });
      })
  }
  render() {
    return (
      <div>
        <h2>Create New Article</h2>
        <form onSubmit={this.handleSubmit}>
            <textarea placeholder="create article" name="content" value={this.state.content} onChange={this.handleChange}>
            </textarea>
            <button type="submit">create</button>
          </form>
      </div>
    );
  }
}
 
export default newArticle;

src/article.js

Now I would like the fact, that once I click on certain article, I am redirected to a page that contains only that specific article. This file allows us to do exactly that. We are making a call to our back-end API to get specific file.
import React, { Component } from "react";
import {
  Route,
  NavLink,
  HashRouter
} from "react-router-dom";
import axios from 'axios';



class article extends Component {
  state = {
    article: String,
    author: String,
    id: String
  }

  componentDidMount() {
    const { id } =  this.props.match.params
    axios.get(`http://localhost:4000/article/${id}`)
      .then(res => {
        const a = res.data;
        console.log(a);
        this.setState({ article: a.content , author: a.author , id: a.id });
      })
  } 
  render() {

    return (
      <div>
                   { this.state.article }
      </div>
    );
  }
}
 
export default article;

We are done with our application. You can go to terminal to power them up and chec it out. It would look something like this.

Tuesday, April 28, 2020

Friday, April 24, 2020

Stolen

"Three minutes to the train," thought Rakesh. It had been a tiring day for him. His job at the dockyard, which was initially hard on him, had gotten easier with time. Earlier, it was a strange caricature of decay and resurrection, but after his first salary was credited a few days ago, the same structure turned into the sweaty smell of hope. Somehow, he had found a home in the blood-metal sound of machines and the ocean's blue water and skies. He did not particularly enjoy coming to the railway station, though. The railway station always made him envious of the lives other people had—families saying affectionate goodbyes, girlfriends holding hands with their boyfriends, and a group of young men cackling with laughter and merriment. It was this envy that made him buy an expensive new smartphone with his first salary. He wanted to feel more confident among the crowd around him. He had already imagined himself standing beside the pole of the Mumbai local train, earphones in his ears, and the wind blowing through his hair. The fact that he owned such an expensive piece of technology made him beam with happiness and joy. He had touched his front pocket jeans countless times, partly because he wanted to be sure that he had one and partly just to enjoy its feel in his pocket. 

"Pooooo..." whistled the train. Rakesh looked up toward the arriving train. Finally, he was going home. He raised his suitcase over his head so that he could fight his way into the general coach of the train. It's amazing to see how quickly people coalesce to get into the general coach of the train. Rakesh nudged around with his elbows as he tried to get on board. In the midst of elbow-kicking and chest foreplay, he saw the familiar face of Mr. Patloo. Mr. Patloo was a 40-year-old man with five strands of hair on his head. He wore a colorful T-shirt and tight-fitted jeans. You did not have to look closely to understand that he was a textbook example of midlife crisis. Oblivious to his bizarre sense of fashion, Mr. Patloo greeted Rakesh with a wide, affectionate smile as both of them fought their way through the crowd. Somehow, they were lucky enough to be inside the train. The general coach of the bogie is a different type of caricature in itself. As you pass, you can smell the different body odors mixed on the bogie.

Thursday, April 9, 2020

Dynamic Programming

In this blog post we will discuss various dynamic programming questions. The idea is to have a same template to understand all the dynamic programming problems. All the problems that we discuss will be divided into four parts:-

  • What is the question?  (read * 2 times
  • Why this problem can be solved with the help of Dynamic Programming? (read once)
  • What does dp[i][j] or dp[i] mean with respect to the question? (read once)
  • What is the solution if the assumed dp array is to be constructed? (read once)
  • How the dp[i] or dp[i][j] will be formulated? Along with the help of an example. (read twice)
  • Variations to the questions 
Once these algorithms are done, we will observe that even the new problems can be solved with the help of this template. I have used same terminology to make the questions easier. 

1. Longest Common Subsequnce

QUESTION : Given two sequences, find the length of longest subsequence present in both of them. In the code given below we assume X,Y to be strings.

WHY DP:  Notice that given problem can be broken down as smaller chunk problem. Let us just take the first character of both the strings and compare them. Then we take the next character of string 1 and compare it with string 2 and so on.

DP[i][j]: 
for the string s1[0..i] and string s2[0..j] what is the length of longest common subsequence with those specific substrings.  Example let string 1 be  "abcdefg" anf string 2 be "abcdgk"





SOLUTION:   dp[n][m] (initialized as  dp[n+1][m+1]

CODE:
https://github.com/vaibhavgeek/tompetitive/blob/master/dynamicProgramming/lcs.cpp


        if (i == 0 || j == 0)  
            dp[i][j] = 0;  

        else if (X[i - 1] == Y[j - 1])  
            dp[i][j] = dp[i - 1][j - 1] + 1;  

        else
            dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);

Variations:- 
  • Printing Longest Common Subsequence
  • Longest Common Subsequence with at most k changes allowed

 2. Maximum Sum Subarray

Tha maximum sum subarray is the task of finding the largest possible sum of a contagious subarray, within a given one-dimensional array A[1..n]. (No length specified)
    dp[i] = max(dp[i-1] + a[i] , a[i])
The maximum subarray problem is the task of finding the largest possible sum of a contiguous subarray, within a given one-dimensional array A[1…n] of numbers with k length.
    dp[i] = dp[i-1] + a[i] - a[i-k-1]

3. Longest Increasing Subsequence

The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order.


    if(arr[j] < arr[i])
        dp[i] = max(dp[i], dp[j] + 1)

4. KnapSack Problem


Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item, or don’t pick it (0-1 property)
In this problem we define dp[i][j] as i value and for j knapsack capacity. That is for j capacity how much maximum value it can store.
if( j < wt[i]) 
        dp[i][j] = dp[i-1][j];
    else 
        dp[i][j] = max(dp[i-1][j - wt[i]] + val[i] , dp[i-1][j]);

5. Coinchange Problem

Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter.
    if(j >= coin[i])
     {
        dp[i][j] = min(1 + dp[i][j-coin[i]] , dp[i-1][j]);
     }
     else
     {
           dp[i][j] = dp[i-1][j];
     }

5. Wordbreak Problem

 

Wednesday, March 18, 2020

Saturday, March 7, 2020

VIM Tutorial - Everything you need to know #1

So you have heard way too much about vim and have given it a go but it turns out that you have given it up after trying it for two days, the reason being you just cannot get used to this new way editing software! You probably already know how to shift between "escape" and "insert" mode of VIM.


COPY PASTE COMMANDS IN VIM

yy Yank (copy) the current line, including the newline character.
dd, Delete (cut) the current line, including the newline character.
p (paste) the text after the cursor


SCREEN SPLITTING.

Ctrl+WS (upper case) for horizontal splitting
Ctrl+Wv (lower case) for vertical splitting
Ctrl+WQ to close one
Ctrl+WCtrl+W to switch between windows
Ctrl+WJ (xor KHL) to switch to adjacent window (intuitively up, down, left, right)

Sunday, February 16, 2020

The lies we have been told

Initially, I thought of writing an article titled "things I wish I had known five years earlier" but honestly speaking most of them I had already known. Also, this article is intentionally written in Hinglish so to have a more realistic feel with the narrative.

Disclaimer: Views can be biased, keep your own judgment with you while reading it.

1.) CGPA 

I vividly remember my seniors giving this advice to me "agar job chahiye toh cg matter nahi karta but research me jaana hai toh kam se kam 8 lana padega". Everyone nodded their head in agreement as if no truer words had ever been spoken before.

For the next five years every time during the exams I asked myself the purpose of "hacking" the previous years' question paper so that I could repeat the same process during examination Hall.  Well, ideally this shouldn't have been the case. Ideally, learning should be equivalent to scoring high marks in an exam. But that's not the case. Not for anyone.

Experience tells us that the best way to study for an examination is to make the list of probable things that will come in the exam, understand them, practice enough problems to cover the range of expected questions and deliver during the examination. The problem with hacking the question paper is that knowledge often is retained just for the duration of the examination, and even if you remember parts of it later, the breadth and depth of the topic is somewhere lost. So clearly examinations aren't the best way to test if a person is learning something or not and yet we tend to study the most just before a test. Hence, order to increase the growth rate in learning there needs to be examination conducted.

You solve previous year paper, you can pass the exam. You solve the previous 5 year papers, you get a distinction. You solve the previous 10 year papers you can probably help the teacher set the question paper for your batch. The only way one can make the tests unhackable is not to increase the difficulty level of the exams (as is assumed by many) but to make them optional. If we are not compelled to study something, we won't do it out of pressure but we will do it for a higher belief system, thus ensuring contentment with our learning experience. Now, keeping students engaged and interested all the time would require newer initiatives and creative solutions in approaches to teaching which is indeed a hard task to accomplish, and I do not think it is right thing to blame teachers for that (Note that I am presenting this point of view just to discard it later is because many of the students believe in it) but instead, make CGPA matter way less than it already does. CGPA should be a metric to guide students rather than a fail-safe mechanism of promotion/demotion. Just like how a gym trainer guides its' incubees. They advise them on follow up course of action depending on the individual requirements rather than kick them out of the gym.

“Study hard what interests you the most in the most undisciplined, irreverent and original manner possible.” ― Richard Feynmann

2.) Happiness 

In the last 50 years(1970-2020), we have seen the advent of technology, and very few deaths because of famine/wars as compared to the previous 50 years (1900-1970). Fewer humans are dying because of starvation. More and more people have access to basic needs such as roti, kapda and makaan. Yet suicides rates are through the roof. Before 1950, suicide rates in countries such as Japan, New Zealand and France was one in 100,000 but today it has increased to a whopping 25 people in 100,000. The reason is pretty simple when economic prosperity happens, expectations ballon. People don't get depressed because of external happenings but from failures internally. Going forward into the century even if the government provides free food for all, cure us of all diseases, ensure world peace, free electricity and internet access to all, it will probably ballon the expectations that people have from themselves, thus leading to more misery.  According to John Stuart Mill "happiness is nothing but pleasure and freedom from pain, and that beyond pleasure and pain there is no good and no evil. Anyone who tries to deduce good and evil from something else (such as the word of God, or the national interest) is fooling you, and perhaps fooling himself too". So, we are biologically entitled to increase our pleasant sensations, the problem is pleasant sensations are like a drug that needs to upgraded with every high you have. Let's assume you feel high after eating a dessert you have craved for long. You end up having it on a regular basis, you won't feel the same high in your second, third eatings. You will crave for more. You will crave for a better dessert and that search will make you miserable.
So what should we do? Aim for less!? Doesn't that sound like losing? No. That's not my point. My point is that pleasure would only feel like pleasure if it is constrained for an aeon of time. Repeated pleasure is nothing but pain.

And when solutions are easy and plenty, we do look out for repeated pleasures.



3.) Technology 

I recently saw a video from 1989 which talked about how our world in 2020 would look like. It talked about flying cars, home automation system and voice-activated circuits. I am not sure about that but 2020 has seen a rise of mobile applications such as Snapchat, Twitter, Reddit, Youtube in ways that wasn't imagined in 1989.  

Wednesday, January 15, 2020

Thursday, January 9, 2020

Indiahikes Brahmatal Trek

There wasn't much of a purpose or expectation with this trip, I just wanted to have a great time. And I did. :-)


Day 1
The day began with my journey from Delhi to Rishikesh which was lot more colder than I had anticipated. The bus was shivering and the engine making crude noises from time to time. All of the road journeys made the vehicles dance to the tune of nature, as if trying to tell us that here nature rules and not the automobile technology. When I reached Rishikesh it was already dark and I had nothing to do except to have dinner and sleep in the comfort of my blanket.


Day 2
The second day was our journey from Rishikesh to Lohajung. I made that journey in a tempo traveller which had a seating capacity of 12 folks. The driver of the tempo traveller was a person who had 33 years of driving experience and a temper of 2 year old. He made sure to tell anyone on the road who dare cut him his choicest cuss words with a sheer innocence that could make an ice cube melt. He was an epilogue to the famous gormint aunty. Midway through our ride, the tempo traveller decided to catch a cold and refused to budge (coupler shaft axle mumbo jumbo, but I don't get it and you really don't care) but with some dcold total from the mechanic, it was ready to go. It was already dark when we reached lohajung and the cold was right up at our hotel alley. A tasty dinner of paneer and daal awaited us at lohajung. After a small pep talk by our trek leader on death and small injuries such as losing a hand we were on our way to Brahmatal top. Or were we?



Day 3
The only thing you will hate more than washing your hands in winter of Himalayas is waking up in the morning. Do I really need to wake up? Why can't they just use helicopter to transfer us to Brahmatal top. None of the pep talk by our trek leader had anything about the waking up in the morning while explaining the dangers involved in this journey which I honestly think is a little unfair. After a quick breakfast we started for bekatlal, our second campsite. The journey from lohajung to bekatlal was 5 kms and a memorable one. We caught glimpses of some homes and saw women carrying 10kgs of some plant as if it's a piece of cake while we were busy making inquiries about the khacchar wala who could carry our luggage so that we can drowse ourselves in nature. I wondered what sort of credit cards do they have? Survival had a simpler meaning for them :- staying alive, getting food for the next day and taking care of the loved ones. Quite a contrast to where all of us were coming from, a world of dopamine inducing mobile applications which can induce stress and anxiety anytime, anyplace and anywhere. The same way farming was a lie to human civilization, internet is a lie to human connection. Musing through some of these random thoughts of mine, we reached bekatlal and the campsite was beautiful with tents to take a shit in and a proper kitchen. We had lunch, played games, sang old songs, sang some new songs and some regional songs as well. One thing about the mountains is that it gets dark before you know it. And dark means good food and cool breeze. Although the place was cold the people were warm with emotions and we all became a group of friends very quickly.




Day 4
Well, after a rugged sleep we all woke up to ankle deep snow at our campsite. All of us rejoiced and did an action pack performance of snowfight which can put any Salman Khan movie to shame. The fun did not last for long as we heard the news that the snowfall is expected to continue in coming days and we won't be able to make it to telundi if that's the case. We made a quick journey to bekatlal lake during which we saw heavy snowfall and a decision was made by our guides and trek leader that we should head back to the basecamp. The sheer excitement of snow turned to a frail expression to accept the reality of nature and move on the basecamp.





Day 5
We started back to Rishikesh thinking that the trek is over but in mountains the experiences are infinite and we had an amazing time during our journey, rejoicing our new found freindships. Everything about Rishikesh is scenic. The people friendly and everyone is a yaatri trying to find God, peace, Beatles Ashram, a cheap mode of transport or tasty ramfal. The iconic duo ramjhula and lakshman jhula are what you will traverse through multiple times during your stay at this beautiful place and somehow the narrow stones of cobblestone will become a cherished memory. We all went to the beatles ashram (a place where beatles have written many of the iconic songs including let it be ) and did some crazy videograaphy and photography.



It's long time coming anyways. So heree we goooo, The problem with today's society is that the fact that we have been trying to live under a big rock trying to hide our emotions. The access to laser fast communications has made us numb any emotion we want and demand an instant sense of gratification to our needs. Even a small hope makes us feel a beat and then leads us to being afraid of ourselves, our actions and mistakes. So it makes sense to take your dreams and run away with them.It's great to be smart, to be disciplined but it's far more important to have fun. It's important to take away relationships from our experiences, to let ourselves emotionally vulnerable and learn little about the world. The trek made me extremely grateful of the fact that I am alive, the fact that I have what I have and last two days have been nothing but rundown fever from the hangover of such a great experience. If you made it this far, thank youuu... :-)