About educcess

Posts by educcess:

PostgreSQL: ERROR: SequelizeDatabaseError operator does not exist character varying = bigint1

Getting this Error for find query using sequelize library in nodejs:

Error: SequelizeDatabaseError: operator does not exist: character varying = bigint1

My Sequelize Database Model looks as follows

<code>const sequelizeHelper = require("../helpers/sequelizeHelper");
const db = sequelizeHelper.db;
const sqlOperator = sequelizeHelper.sqlOperator;
const UserRolesModel = require("./UserRolesModel");

const UserModel = db.define(
  "users",
  {
    userId: {
      field: "userId",
      type: sqlOperator.UUID,
      primaryKey: true,
      defaultValue: sqlOperator.UUIDV4
    },
    firstName: {
      field: "firstName",
      type: sqlOperator.STRING(100),
      require: true
    },
    lastName: {
      field: "lastName",
      type: sqlOperator.STRING(100),
    },
    email: {
      field: "email",
      type: sqlOperator.STRING(1025),
      validate: {
        isEmail: true
      }
    },
    userName: {
      field: "userName",
      type: sqlOperator.STRING(1025),
    },
    phone: {
      field: "phone",
      type: sqlOperator.STRING(13),
    },
    photo: {
      field: "photo",
      type: sqlOperator.STRING(1024),
      defaultValue: null,
      validate: {
        isUrl: true
      }
    },
    studentDetails: {
      field: "studentDetails",
      type: sqlOperator.JSON,
      defaultValue: null,
    },
    profession: {
      field: "profession",
      type: sqlOperator.STRING(13),
      defaultValue: ""
    },
  },
  {
    tableName: "users",
    timestamps: true,
    indexes: &#91;
      {
        unique: true,
        fields: &#91;"email"],
        name: "user_email_unique_index"
      },
      {
        unique: true,
        fields: &#91;"userName"],
        name: "user_user_name_unique_index"
      },
    ]
  }
);

UserModel.associate = () => {
  UserModel.hasMany(UserRolesModel, {
    as: "roles"
  });
  UserModel.sync({ alter: true });  
}
module.exports = UserModel;
</code>

Solution:

This kind of issue usually occur when we try to compare mismatched data types. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I’m guessing SQLServer does typecasting automagically (which is a bad thing).

<code>const phone = 9998886660;
UserModel.count({
      where: {
        phone: phone
      }
    });</code>

The above code throws operator does not exist: integer = character varying exception, because we are trying to compare integer with string. To fix this issue change as follows

<code>const phone = "9998886660"; //this will fix the issue
UserModel.count({
      where: {
        phone: phone
      }
    });</code>

For other sequelize errors: Read More Here

Server Side Rendering using React16, material-ui and redux Video Tutorial

Complete Source Code for server side rendering in ReactJS using material-ui and redux is explained step by step here

You can also see details about each code segment and download source code from github here

Life Beyond Structure, Analysis, program and computers

I found this wonderful video and found the meaning of life, you may be a programmer, a civil engineer, a car maker, a researcher, a teacher or a student whoever you may be, but one must listen to this talk by Prof. Devdas Menon, Department of Civil Engineering, IIT Madras

Some of the very interesting point taken out from this video are as follows

George Calvin’s famouse quote in 80’s
The paradox of our time and history is that


We tall the buildings but short the temper,
wide our free ways but narrowed our view point
we spend more but we have less
we buy more but we enjoy less
we have bigger houses but smaller family
we have more knowledge but less judgement
we have more experts but yet more problems
we have more medicines but less wellness
we multiplied our positions but reduced our values
we talk too much , drive too fast , stay up too late, getup too tired, we have reached moon and back to earth but trouble crossing a road to meet a neighbour,
we have conquered outer space but not inner space
we have done larger things but not better
we have learnt to rush but not to wait
we have fast food but slow digestion
a big men but small character
too many young couple but more divorces
more entertainment but less happiness

MASLOW’s Hierarchy Of Needs

Matthieu Ricard’s Quote

A French Scientist, who turned as tibetan monk

We all tried consciously or unconsciously, competently or clumsily , Passionately or calmly, adventurously or routinely to be Happier, Yet we more often confuse the genuine happiness with merely seeking enjoyable sensation. Happiness is state of inner fulfilment but not the gratification of inexhaustible desire for outer things. This is traditional wisdom.

Kabir Das Said it beautifully in 15th century in one of his famous doha as

कस्तूरी कुंडल बसे,मृग ढूँढत बन माही। ज्योज्यो घट– घट राम है,दुनिया देखें नाही ।।

Listen to this nice video by Prof. Devdas Menon, Department of Civil Engineering, IIT Madras

java.lang.BootstrapMethodError: Exception from call site bootstrap method

Exception – BootstrapMethodError: while parsing CSV using OpenCSV in Android App

<code>
java.lang.BootstrapMethodError: Exception from call site #30 bootstrap method
        at org.apache.commons.lang3.Validate.notNull(Validate.java:225)
        at org.apache.commons.lang3.reflect.FieldUtils.getAllFieldsList(FieldUtils.java:217)
        at org.apache.commons.lang3.reflect.FieldUtils.getAllFields(FieldUtils.java:202)
        at com.opencsv.bean.util.OpencsvUtils.determineMappingStrategy(OpencsvUtils.java:66)
        at com.opencsv.bean.CsvToBeanBuilder.build(CsvToBeanBuilder.java:210)
        at com.example.rkmmedialibrary.MainActivity.importCsv(MainActivity.java:95)
        at com.example.rkmmedialibrary.MainActivity.onActivityResult(MainActivity.java:80)
        at android.app.Activity.dispatchActivityResult(Activity.java:7454)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4353)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4402)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.ClassCastException: Bootstrap method returned null
</code>

Solution: for BootstrapMethodError

The issue is probably due to Java Version Mismatch, Kindly add below code in your build.gradle file

<code>
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
</code>

Reference: SO Post

Sequelize: Using “Include” when we are joining same table multiple times.

“Include” with single join

Let us first see how we can use include when we are joining 2 simple tables.

Note: If you are already aware of single join, then jump to section “Include” with multiple joins

Consider the following two tables,

User Table

<code>const UserModel = db.define(
  "users",
  {
    userId: {
      field: "userId",
      type: sqlOperator.UUID,
      primaryKey: true,
      defaultValue: sqlOperator.UUIDV4
    },
    firstName: {
      field: "firstName",
      type: sqlOperator.STRING(100),
      require: true
    },
    lastName: {
      field: "lastName",
      type: sqlOperator.STRING(100),
    },
    email: {
      field: "email",
      type: sqlOperator.STRING(255),
      validate: {
        isEmail: true
      }
    },
    {
    tableName: "users",
    timestamps: true
  }
);</code>

Notice Table

<code>const NoticesModel = db.define(
  "notices",
  {
    noticeId: {
      field: "noticeId",
      type: sqlOperator.UUID,
      primaryKey: true,
      defaultValue: sqlOperator.UUIDV4
    },
    title : {
      field: "title",
      type: sqlOperator.STRING(250),
    },
    notice : {
      field: "notice",
      type: sqlOperator.TEXT,
    }
  },
  {
    tableName: "notices",
    timestamps: true
  }
);

NoticesModel.belongsTo(UserModel, {
    foreignKey : {
      name : "noticeBy",
      allowNull: false
    },
    targetKey: "userId"
  });</code>

When we want to fetch the user who has posted the notice, we will use the following code,

<code>const query &#91;"include"] = &#91;{model: UserModel}]
// query can include all some conditions required, this is out of scope of this tutorial, for the same you can check out this 
const notices = await NoticeModel.findAll(query);</code>

Reference

After executing the above findAll, we will get all the notices and the respective user who has created that.

“Include” with multiple joins

In this section we will learn how to use when there are multiple join of the same table.

We will make some changes in the Notice table as follows,

<code>const NoticesModel = db.define(
  "notices",
  {
    noticeId: {
      field: "noticeId",
      type: sqlOperator.UUID,
      primaryKey: true,
      defaultValue: sqlOperator.UUIDV4
    },
    title : {
      field: "title",
      type: sqlOperator.STRING(250),
    },
    notice : {
      field: "notice",
      type: sqlOperator.TEXT,
    }
  },
  {
    tableName: "notices",
    timestamps: true
  }
);

NoticesModel.belongsTo(UserModel, {
    foreignKey : {
      name : "noticeBy",
      allowNull: false
    },
    targetKey: "userId"
  });

//Added one more new relation
NoticesModel.belongsTo(UserModel, {
    foreignKey : {
      name : "noticeTo",
      allowNull: false
    },
    targetKey: "userId"
  });</code>

Now we will try to run the same above findAll, we will observe that neither noticeTo nor noticeBy will be filled.

What is happening here is Sequelize finds multiple userModels so it will not be sure which one to fetch.

Solution

To solve the above issue we will have to make the following changes

<code>const NoticesModel = db.define(
  "notices",
  {
    noticeId: {
      field: "noticeId",
      type: sqlOperator.UUID,
      primaryKey: true,
      defaultValue: sqlOperator.UUIDV4
    },
    title : {
      field: "title",
      type: sqlOperator.STRING(250),
    },
    notice : {
      field: "notice",
      type: sqlOperator.TEXT,
    }
  },
  {
    tableName: "notices",
    timestamps: true
  }
);

NoticesModel.belongsTo(UserModel, {
    foreignKey : {
      name : "noticeBy",
      allowNull: false
    },
    targetKey: "userId",
    as : "noticedBy"
  });

//Added one more new relation
NoticesModel.belongsTo(UserModel, {
    foreignKey : {
      name : "noticeTo",
      allowNull: false
    },
    as: "noticedTo",
    targetKey: "userId"
  });</code>

And in the find we will do this,

const query[&quot;include&quot;] = [{model: UserModel, as: &quot;noticedBy&quot;}, {model: UserModel, as: &quot;noticedTo&quot;}]

const notices = await NoticeModel.findAll(query);

Once we add the above changes, both noticedBy and noticeTo will be filled. (Observe we have not kept the alias name same, we have changed them slightly).

Possible errors

uncaughtException: Naming collision between attribute ‘noticeTo’ and association ‘noticeTo’ on model notices. To remedy this, change either foreignKey or as in your association definition\nError: Naming collision between attribute ‘noticeTo’ and association ‘noticeTo’ on model notices

What does the above error mean?

It says that we have given same names to the attribute i.e foreign key and alias. We get this with the following code,

<code>  NoticesModel.belongsTo(UserModel, {
    foreignKey: "noticeTo",
    as: "noticeTo",
    targetKey: "userId"
  });</code>

As we can see the highlighted rows, both have the same names. Solution to this is very simple, just rename alias to something else.

<code>  NoticesModel.belongsTo(UserModel, {
    foreignKey: "noticeTo",
    as: "noticedTo",
    targetKey: "userId"
  });</code>

TADA!!! everything will work fine now.

For More Sequelize Errors: Read More Here

React16 Server Side Rendering (SSR) CSS and Images Not Loading Issues

Before looking into React16 SSR css and images related issues first check go through a Step By Step guide for implementing React16 Server Side Rendering (SSR) with Material-ui library

React16 SSR css & public images not loading issue

Since in SSR applications we configure our own http server using expressjs or any other framework, we have to configure the path for public folder and css files folder path so that http server finds the file when request comes.

To fix css and public images not loading issue which is a very common issues in react ssr applications, we have to add following below lines in our server side script

<code>//note the relative path of build folder  may change as per your project structure check those ../.. as per your project.
app.use(express.static(path.join(__dirname, '../../build'))); 
app.use(express.static(path.join(__dirname, 'public')));</code>

if above two lines are not added in your server side script then you may face following common issues.

  1. Bootstrap/jquery css files are not getting included after running npm run build and running the app
  2. images referred from public folder will not be loaded

ComponentDidMount not getting called in React SSR application

Another very common problem in react ssr applications is once we enable server side rendering client side rendering will stop happening. Since client side rendering doesn’t happen componentDidMount will not be fired some times.

React run build generates lots of javascript files under build/static/js folder, if these files are not served by our server side script when browser requests those files then client side rendering fails. when we generate build using npm run build, react-scripts refers those static js files in index.html file. When page is loaded browser requests for those js files but our server side script fails to serve those files.

again to solve this issue the above two lines code is important especially,

<code>//note the relative path of build folder  may change as per your project structure check those ../.. as per your project.
app.use(express.static(path.join(__dirname, '../../build')));</code>

COVID-19 : corona virus epidemic, What one can do to stop it?

The world has hit badly by an invisible tiny virus who is shaking the entire scientific, medical community and challenging to save the lives. Corona virus is not that critical if every one takes some simple precautions but as usual we did mistakes, we neglected and hence paying for it and struggling to escape from it.

Coronavirus is spreading very fast, its an exponential way, person to person through different medium and hence an extreme precautions has to be taken to stop it

Social Distancing:

A simple technique can save our life and save your family, social distancing. Virus can spread through person to person when a infected person cough, spit, sneezes.

It will also spread through some surfaces when an infected person touch any metal surface, cardboard, plastic the virus can survive several hours on the surface and some one else touch the same surface it will transfer to his body.

Look at the below animated view which helps us to understand how social distancing helps us to stop coronavirus spread drastically

Is’t it a simple solution ? but we are failing follow.

“By our most conservative estimate, at least 59% of the infected individuals were out and about, without being tested and potentially infecting others,” says lead study author Prof. Wu Tangchun. Reference

What you should not do ?

Avoid

  1. Parties, functions
  2. Smoking
  3. Avoid taking tablets on your own for fever , cold or headache.
  4. touching your eyes, nose and mouth without washing it properly with soap and water or sanitisers

Social Warriors and NGOs working for Covid-19

There are lot of NGOs, social warriors working for coronavirus epidemic to stop it, lot of awareness programs running for COVID-19, lot of donations are being raised by many organisations to help the needy people in this lockdown situation almost everywhere in the world

Awareness Programs Run by SociallyGood Platform through some of the organisations

Awareness Campaign For Pandemic COVID-19

Awareness program by Sewa USA :

Coronavirus-(COVID-19) Awareness Program

Donate for Covid-19 epidemic

Donation Campaigns run by SociallyGood Platform through some of the organisations

Groceries to daily wage workers in view of outbreak of COVID-19

Support to Fight COVID-19

know more about COVID-19 through SociallyGood Platform

COVID-19 Campaigns on SociallyGood Platform

Let us stop Coronavirus by following the protocol

  1. Lockdown : Be at home, do not go out without the real need
  2. Social Distancing: Keep distance between people
  3. Be wise not panic
  4. Improve your health by doing simple physical work like yoga

COVID-19 Information Center on Facebook