Archive for the ‘Programming’ Category

JavaScript’s Internal representation of Objects

Wednesday, April 15th, 2020

 

A simple diagram is probably the best way to give a quick overview of the object representation in Javascript.

Most objects contain all their properties in a single block of memory (“a”, and “b”). All blocks of memory have a pointer to a map, which describes their structure.
Named properties that don’t fit in an object are usually stored in an overflow array (“c”, and “d”).
Numbered properties are stored separately, usually in a contiguous array.

The JavaScript standard allows developers to define objects in a very flexible way, and it is hard to come up with an efficient representation that works for everything. An object is essentially a collection of properties: basically key-value pairs. You can access properties using two different kinds of expressions:

  • obj.prop
  • obj[“prop”]

According to the spec, property names are always strings. If you use a name which is not a string, it is implicitly converted to a string. This may be a little surprising: if you use a number as a property name, it gets converted to a string as well (at least according to the spec). Because of this, you can store values at negative or fractional array indices. So a JavaScript object is basically a map from strings to values.

 

Javascript as a Full Stack Language

Thursday, April 2nd, 2020

Javascript is a scripting language. JavaScript is interpreted and sometimes compiled at run time. It runs natively on your browser which makes it completely cross platform and hardware agnostic.

Javascript is the de facto language used to code the front end interface for web apps. There are many Javascript frameworks which do exactly that. Moreover JavaScript can also be run in a server environment using NodeJs.

JavaScript runs on the client side of the web, which can be used to design / program how the web pages behave on the occurrence of an event. JavaScript is an easy to learn and also powerful scripting language, widely used for controlling web page behavior.

Generally, JavaScript frameworks will do the heavy lifting when it comes to binding your data to your mark-up. You have a model of data, and you have some mark-up to which you’d like to bind it. You can achieve this in vanilla JavaScript yourself if you wish, but a framework such as Angular or React will cater for it most of the time.

With a framework, you’re just doing things faster. You can use all these battle-tested libraries. They’ve been checked for security, they’re in use on a thousand of different websites, they’ve been checked for performance, edge case bugs, so you don’t have to find those bugs over and over again because they’re already been found and fixed.

Another common application for JavaScript is as a (Web) server side scripting language. A JavaScript web server would expose host objects representing a HTTP request and response objects, which could then be manipulated by a JavaScript program to dynamically generate web pages. Node.js is a popular example of this.

Node.js is a platform built on Chrome’s JavaScript run time for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

In the database side of application development, Javascript also has an offering. Mongo DB has rapidly grown to become a popular database for web applications and is a perfect fit for Node.JS applications, letting you write Javascript for the client, backend and database layer. Its schemaless nature is a better match to our constantly evolving data structures in web applications, and the integrated support for location queries is a bonus that’s hard to ignore.

What is Full Stack Development ?

Sunday, March 29th, 2020

A software developer usually works on more than one platform or technologies in the organization he is working on. But those platforms or technologies usually fall under two categories.

The Front End and the Back End. Or Client Side and Server Side.

Front End Development
The front end is everything to do with what the user sees, including design of web pages, user interfaces and the entire user experience. Designing and maintaining the user experience is an important part of any software product, and it’s generally referred to as Front End Development.
Front End Technologies are HTML, CSS, Vue.JS, EmberJS, etc.

Back End Development
The back end, or the “server-side”, is basically how the software product works, updates, and changes. This refers to everything the user can’t see in their interface, like databases and servers.
Developing and maintaining the databases, servers and of course the actual business logic of the application is known as back end development.
Back End Technologies are much more varied. We have PHP, .NET, Java, Python, NodeJS and many more. It usually comes down to developer preference as all these tools are quite versatile.

In an application like Google Maps the Front End would be the actual application on your Android or iOS phone. The ability to scroll, pan across the loaded area of the maps, the option to search for locations and type in your destination are all to do with the front end. But once you’ve typed in your destination, the back end takes over. The data from the GPS module on your phone and your typed in destination are sent to Google’s servers. The back end receives this data. It determines your current location from the longitude and latitude values from your GPS. It determines the shortest route to your preferred destination. It also calculates all alternative routes and sends it back to your mobile phone. Then the front end takes the responsibility of displaying the optimal route along with alternatives in an easy to understand at a glance format.

Full Stack Development

Full stack developers have the ability to design complete web application and websites. They work on both the front end and the back end of their product of application. It naturally follows that they are well versed in technologies of both categories.

A technology stack is the set of technologies used to build an application. A technology stack usually comprises of a Server Platform, a Front End framework, a Back End language and a Database.

Here are the most popular Full Stacks used:
MEAN Stack: MongoDB, Express, AngularJS and Node.js.
MERN Stack: MongoDB, Express, ReactJS and Node.js
Django Stack: Django, python and MySQL as Database.
Rails or Ruby on Rails: Uses Ruby, PHP and MySQL.
LAMP Stack: Linux, Apache, MySQL and PHP.

[Tutorial] Mouse Macro Maker using jnativehook

Saturday, March 24th, 2018

Clicking can be a mundane task. Especially when you have to do it repeatedly without much thinking. I’m sure a lot of you have felt this. Many applications exist which offer mouse macro capabilities, but what’s the fun in that ?
Lets make our own program which will simplify clicking chores.

Naturally, jnativehook and java.awt.Robot are all we need. Java’s Robot class can effectively move and click your mouse without human intervention and jnativehook allows you to listen to system wide mouse and keyboard calls.

Graphical User Interface :
A simplistic GUI built using Eclipse’s Window Builder plugin should serve us well.

A button to start/stop recording the macro, one to load and one to save the macro are all we need. An integer spinner to set the delay between playback clicks is an added functionality.

Structure of the Application :
To keep the end code as simple as possible we only use two Java classes here. A Recorder class will be our main class. It implements jnativehook to record mouse clicks and save it in an easily readable text format. A Player class will read the saved macro and execute it using Java’s Robot Class.

 

The project can be found at https://github.com/Vetox/MouseMacroMaker

[Tutorial] Insaniquarium Deluxe Rapid Clicker

Wednesday, November 29th, 2017

Insaniquarium Deluxe is a 2D arcade game released by Flying Bear Entertainment and PopCap Games in 2004. It received huge critical acclaim and positive reviews across the board. It was one of the defining games which rocketed PopCap games to fame before Plants vs Zombies. The player uses the mouse to feed fishes, collect coins and fight aliens. The game revolves around mashing your left mouse button for hours on end until you beat the level. And then you repeat the same process for the next level. This seems like something which can easily be helped.

jnativehook, a java library which acts as a global mouse and keyboard listener could easily reduce the number of clicks we need.

jnativehook allows us to detect keyboard key presses and java’s Robot class allows us to easily simulate mouse clicks. That’s all we need to make Insaniquarium less insane.

Lets code an application which will issue a mouse click at the position of the cursor whenever it detects a specific key being pressed, lets say “S”. If we hold down “S” our program should keep issuing left mouse clicks at the cursor. This rate of clicking will invariably be much faster than physically possible. Thereby making feeding fishes, collecting coins and fighting aliens much easier on us.
We’ll also add the “P” key as a way to exit the program.

Pre requisite :
Include jnativehook in the build path.

GUI :
The GUI is built using the Window Builder plugin for eclipse.

Once a keyboard hook is added, all thats left to do is to override the nativeKeyPressed method:

public void nativeKeyPressed(NativeKeyEvent e) {
if (NativeKeyEvent.getKeyText(e.getKeyCode()).equals("S")) {
try {
Robot r = new Robot();

for (int t = 0; t < 1; t++) {
r.mousePress(InputEvent.BUTTON1_MASK);
r.mouseRelease(InputEvent.BUTTON1_MASK);
}

} catch (Exception e1) {
System.out.println(e1.toString());
}
}

if (NativeKeyEvent.getKeyText(e.getKeyCode()).equals(“P”)) {
try {
GlobalScreen.unregisterNativeHook();
System.exit(1);
} catch (Exception ex) {

}
}
}

When the “S” key is pressed down, it rapidly issues mouse click commands at the position of the cursor. Making it much easier to collect coins and feed fishes in Insaniquarium.

Source Code :
https://github.com/Vetox/RapidClicker

[Tutorial] jnativehook : Control native mouse and keyboard calls outside Java

Wednesday, November 29th, 2017

In programming a “hook” is a way for a programmer to access already existing code and modify it to his specification. A mouse hook in java is quite similar to a MouseListener, except while a MouseListener functions only within the swing or awt component it is bound to, a native mouse hook can intercept mouse calls from all over the system. This makes it immensely useful for various kinds of programs. Here, I’ll try to explain how the jnativehook library can be used to detect mouse and keyboard calls.

jnativehook is an opensource native hook library for Java. It functions as a Global Mouse and Keyboard Listener.

jnativehook can be downloaded from its official GitHub page here :
https://github.com/kwhat/jnativehook/releases
Extract and add jnativehook to your build path.

Mouse Hook :
To use a Mouse Hook in your program, have your class implement NativeMouseInputListener.
Methods to override :
public void nativeMouseClicked(NativeKeyEvent e);
public void nativeMousePressed(NativeKeyEvent e);
public void nativeMouseReleased(NativeKeyEvent e);
public void nativeMouseMoved(NativeKeyEvent e);
public void nativeMouseDragged(NativeKeyEvent e);

These methods are self explanatory. Put the code you want to run when your mouse is clicked, pressed, released, moved or dragged in these methods.

To register jnativehook and cause it to start listening to mouse events globally, enclose this line in a try catch block :
GlobalScreen.registerNativeHook();

To unregister it :
GlobalScreen.unregisterNativeHook();

For a program which detects and outputs which mouse actions have been performed :

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;

public class GlobalMouseListenerExample implements NativeMouseInputListener {
public void nativeMouseClicked(NativeMouseEvent e) {
System.out.println("Mouse Clicked: " + e.getClickCount());
}

public void nativeMousePressed(NativeMouseEvent e) {
System.out.println("Mouse Pressed: " + e.getButton());
}

public void nativeMouseReleased(NativeMouseEvent e) {
System.out.println("Mouse Released: " + e.getButton());
}

public void nativeMouseMoved(NativeMouseEvent e) {
System.out.println("Mouse Moved: " + e.getX() + ", " + e.getY());
}

public void nativeMouseDragged(NativeMouseEvent e) {
System.out.println("Mouse Dragged: " + e.getX() + ", " + e.getY());
}

public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());

System.exit(1);
}

// Construct the example object.
GlobalMouseListenerExample example = new GlobalMouseListenerExample();

// Add the appropriate listeners.
GlobalScreen.addNativeMouseListener(example);
GlobalScreen.addNativeMouseMotionListener(example);
}
}

Similarly for a Keyboard Hook have your class implement NativeKeyListener.
Methods to override :

public void nativeKeyPressed(NativeKeyEvent e)
public void nativeKeyReleased(NativeKeyEvent e)
public void nativeKeyTyped(NativeKeyEvent e)

The method NativeKeyEvent.getKeyText(e.getKeyCode()) will return the key that was pressed. Where e is the NativeKeyEvent accepted by each of the overriden methods.


import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

public class GlobalKeyListenerExample implements NativeKeyListener {
public void nativeKeyPressed(NativeKeyEvent e) {
System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));

if (e.getKeyCode() == NativeKeyEvent.VC_ESCAPE) {
GlobalScreen.unregisterNativeHook();
}
}

public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
}

public void nativeKeyTyped(NativeKeyEvent e) {
System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
}

public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());

System.exit(1);
}

GlobalScreen.addNativeKeyListener(new GlobalKeyListenerExample());
}
}

Overriding the nativeKeyPressed() method like above will output the KeyText of every button pressed. It will also unregister the nativehook if the “ESC” key is pressed.

OpenCV Experiment : Virtual On Screen Drums

Monday, June 12th, 2017

I was recently involved in a lot of Image Processing for a project at college and while I’m no longer interested in what I was working on, I still wanted to do something fun with whatever OpenCV and Image Processing Techniques I had learnt.

I imagined an “On Screen Drums Application” where we use a live video input to detect a “drumstick” we hold up and use to beat on a virtual drum causing it to reverberate depending on how hard we hit it.

Its not too complex and can quite easily be done with some simple OpenCV tricks in Java.

First we receive the video stream and process it frame by frame. We filter each frame for the specific color and shape of the marker on our “drumstick”. In my case, my drumstick is a bright orange ball stuck to a pencil. Once we’ve identified where the marker is, we compare its current position with its position in the previous frame to roughly calculate how fast it’s traveling.

We overlay an image of a drum on the video feed and when the marker touches the overlay, we use Java’s inbuilt MIDI synthesizers to generate drum noises depending on the speed at which the drum overlay was struck.

Identifying the marker :
We first convert the frame to HSV as that color palette is much easier to compute with, rather than RGB.

To identify the marker on the drumstick, start by filtering out its hsv value. A hsv range of (100, 100, 100) to (112, 255, 255) generally captures my marker alone and leaves out most other things.  Anything outside that threshold gets filtered out and that leaves us with just the marker. We run a couple of erode and dilate methods through the filtered image and that leaves us with a blob which is our marker in the frame. We also know the general size of the ball so getting the third moment of the blob would give its size. Checking if the moment is always larger than a fixed number would further eliminate mistakes.

Drawing the Drum overlay:
We use Java’s Graphics class to draw a drum overlay on the video feed. The overlay is an image of a drum cropped down to size and the rest of the screen filled with transparency. It’s saved in png format to preserve transparency.

Generating Drum Beats:
We initialize Java’s MIDI synthesizers and select the channel which sounds best. I liked channel 114 and that’s what I’ve used. I honestly can’t tell the difference between most channels, so it makes no difference to me. We check if the position of the marker intersects with the overlay on screen and if its velocity is greater than a suitable threshold. If so, then we tell Java to bang its virtual drums as hard as we virtually hit it.

The whole project is on my GitHub page at
https://github.com/Vetox/Virtual-On-Screen-Drum

Here are a few screenshots :
The marker on screen with the overlay

The same frame’s HSV image:

The same frame after filtering:

Competitive Programming vs Software Programming

Wednesday, March 15th, 2017

This dilemma always comes up for those college students engrossed in learning programming. What to invest more of their time on? Software programming vis-a-vis competitive programming.

Let’s start by comparing the two.

What is Competitive programming?
Competitive programming is what most college students do to hone their algorithmic knowledge and mastery over various data structures. It not only improves problem solving capability but also augments a person’s speed and accuracy when solving such problems. Competitive programming is basically taking programming up as a sport. Participants are given a set amount of time to solve a number of complex algorithmic questions. It tests a person’s raw thinking capability and ability to grasp problems. It expects an extremely fast solution which need not be the simplest one possible.

What is Software programming?
Software programming is less of a perfect science, compared to the calculated laser precision of competitive programming. You are expected to solve real world problems, in a way that is simple, efficient and also easy to maintain. You are not expected to use complex algorithms to calculate the answer in milliseconds, but to write simple code which gets the job done in reasonable time. Software programming is the development of apps which run on mobile, PC and other platforms.

Now let’s get to the differences between the two :

Competitive Programming

  • The problem is solvable within the given time and constraints using the given resources
  • Short time commitment and instant gratification
  • Skill level is easily quantified

Software Programming

  • The problem “may” be solvable within the given time and constraints using the given resources
  • Long time commitment and gradual gratification
  • Skill level is not easily quantifiable

So which one should you do ?
There is no right answer to this question. Most interviews are composed of algorithmic questions but the actual job will entail more of software programming. So it is obviously healthy to have a good mix of both under your belt by the time you start job hunting, The ratio of that mix is left to you to figure out.

Happy Coding,
Karthikeyan M

Why do we code ?

Saturday, January 21st, 2017

For people, computer programming may mean many things. It could mean their livelihood, their passion, their meal ticket, their escape from reality, a path to a better life or maybe it’s all gibberish to them no matter how you put it. Yeah, people code for many reasons.

But, why do I code ?
Many people do take up competitive programming as it pretty much guarantees you a bigger package than your peers. But those people do not mind the tireless nights, the sleep deprived mania induced by bad logic, the bleary eyed mornings and the thankless hours of effort you put in to climb the leaderboards.

But for the rest of us who are allergic to menial labour and value our sleep over all else, we need something more enticing. Something which gives a greater high than any drug known to man, something which sets the endorphin rushing through your veins, something which causes us to forego our treasured sleep, late night DOTA games, food and social life.

All for that tiny green tick mark called the AC. Once you get your first taste of the “Accepted” sign, you’ll never be able to live without it again. Your body will crave it. You’ll dream about it. You’ll obsess over it like it is the single most important thing in your life. And it may very well be. It drives your very existence. It drives you to learn and re-learn. That is what motivates the best of us. We are coders, and we are all addicted to what we do.

SPOJ Classical Problem FARIDA Dynamic Programming Tutorial

Friday, December 16th, 2016

 

This will be an editorial of the FARIDA problem from SPOJ which is an basic dynamic programming problem. It is easily solved by knowing the initial states and the simple transition from previous states to the next ones.

This problem is from : http://www.spoj.com/problems/FARIDA/

Problem Statement:

Once upon time there was a cute princess called Farida living in a castle with her father, mother and uncle. On the way to the castle there lived many monsters. Each one of them had some gold coins. Although they are monsters they will not hurt. Instead they will give you the gold coins, but if and only if you didn’t take any coins from the monster directly before the current one. To marry princess Farida you have to pass all the monsters and collect as many coins as possible. Given the number of gold coins each monster has, calculate the maximum number of coins you can collect on your way to the castle.

This is the problem faced by FARIDA, a cute princess, many of you would have come across early in your adventure across dynamic programming kingdom. With an acceptance percentage of around 29%. This would be one of the easiest DP problems, but can lay the foundations to better understanding of DP states and their transition.

So, the problem basically reduces to :

Given an array, output the maximum sum of elements you can make from a subset of the array such that no two consecutive numbers from the original array are included in the subset.

Now, considering a DP[i] to be the maximum sum obtainable under such conditions till ‘i’ in the array. The DP transitions are intuitively derived as:
DP[i] = Maximum of ( DP[i – 1] ) &  ( DP[i] + element ‘i’ from the array )

If we decide not to include element ‘i’ the maximum obtainable sum up to ‘i’ will be DP[i – 1]. If we decide to include DP[i] then the maximum will be DP[i – 2] + Element ‘i’, since we cant include element ‘i – 1’ in this.
So you can see how the maximum of these two values will give us the general DP recurrence. Then, the initial states easily work out to be
DP[0] = First element in array
DP[1] = Maximum of first and second elements in array.

Lastly including condition for n = 0, and n = 1, the problem is solved.

This should easily bring you an AC and 0.02 points on SPOJ as of writing the article.

The problem BadNeighbours from Top Coder is also very similar to this one.

Here is the Java code to clear things up for you:

import java.util.Scanner;

class FARIDA {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int t = sc.nextInt();
int[] a = new int[t];
for (int j = 0; j < t; j++) {

a[j] = sc.nextInt();

}

long[] dp = new long[t];

if (t == 0) {

System.out.println("Case " + (i + 1) + ": 0");

continue;

}

if (t >= 1) {
dp[0] = a[0];
}
if (t >= 2) {
dp[1] = a[0] > a[1] ? a[0] : a[1];
}
if (t >= 3) {
for (int j = 2; j < t; j++) {
dp[j] = Math.max(dp[j - 1], dp[j - 2] + a[j]);
}
}
System.out.println("Case " + (i + 1) + ": " + dp[dp.length - 1]);
}
}
}