echo $my_thoughts > /dev/null

Code, philosophy and scribblings

8 Signs if Someone's Good at Something

Written in first person perspective for clarity. The list ranges from novice to expert in that order. Exceptions exist, and this is just a list of common symptoms, not a roadmap.

The thing tends to excite you a tad bit more than it does others.

Reading / learning about this thing amuses you.

After a while, you tend to see tiny details others usually ignore.

Creating something yourself related to that thing keeps you in the zone.

You have fun being in that zone.

You can anytime pick creating / learning this thing over a dinner hangout with friends.

You start appreciating what others have done in this field in a much deeper way. That is, you’ve come to see the true genius of someone’s work. Not because the rest of the community appreciates his / her work.

You create stuff, that folks in that field find interesting and useful.

Awesome Compiler Resources

Blogs

Implementing a Simple Compiler on 25 Lines of JavaScript

Developing Statically Typed Programming Language

Let’s Build An Interpreter

Let’s Build A Compiler

Compiler Basics - Series

Write Your Own Programming Language & Compiler In Python

Introduction To LLVM

Just Read These Two Papers To Build A Compiler

http://turbopascal.org/ (Pascal compiler internals)

http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/ (A quick intro to expression parsing, grammars, and stuff)

https://github.com/melling/ComputerLanguages/blob/master/compilers.md (HN Links)

Experience of folks who’ve tried building compilers

I Built a Lisp Compiler

https://blog.sigplan.org/2019/07/09/my-first-fifteen-compilers/

Books

https://craftinginterpreters.com/

https://interpreterbook.com/ (paid book)

http://www.buildyourownlisp.com/contents

https://holub.com/compiler/

https://t3x.org/t3x/book.html

Courses

https://lagunita.stanford.edu/courses/Engineering/Compilers/Fall2014/about

https://www.dabeaz.com/compiler.html

Tools

https://t3x.org/t3x/book.html

Questions to Ask Before Joining a Startup

I can’t boil it down to 3 because there are many things you need to understand, some details can be gleaned via observation too.

So some of the top questions you should ask IMO are below:

Runway left?

When was the last raise, what was the amount and time to raise it? What is the makeup of the investors (Angel vs. VC etc)?

What is the next milestone on the fundraising side?

What is the biggest competitive advantage/product feature the company has?

What are the biggest issues facing product/development?

How do you see my role in helping the company?

How can I best help the company if I come aboard?

What is the biggest opportunity you feel the company has?

What is the biggest risk the company faces?

Who do I report to? – this trips some startups up but can highlight potential issues.

How many employees are there today? How many do you plan to hire in the next 3, 6, 12 months? How many employees have left since founding?

Equity and the vesting schedule details. Share class information as well. Current dilution, outstanding shares issued and reserved is nice to know too as well.

For what it is worth and this applies to any size company, not just startups, you should also ask about what agreements they want you to sign and get them as early into the process as possible without being unreasonable. e.g. outside work policy, NDA, non-compete, non-solicitation, compensation, equity, etc. Some of these they may not give you until you agree at least conditionally verbally, but there should be no reason you can’t see them once you do. Companies that hide these until your first day make me nervous, at the same time that doesn’t mean they are bad, just maybe been given bad advice or have a lack of understanding themselves.

This entire thread is gold. This is a direct rip off from the top most comment. Bookmarking it here for reference.

How to Install & Use ProseMirror in Your Project

Prosemirror is an incredibly well-written rich text library. But, lacks proper prose on how to set it up in a project for beginner / occasional JS developers. By the time you’ve finished reading this you’d learn:

+ How to install prosemirror into your JS codebase (that isn't using fancy modern tools like Webpack, Babel, etc currently).
+ Why the installation is difficult.
+ Some modern JS practices.

This piece is intended for non full-time JS developers who were familiar with Javascript in its jQuery and <script> tag and ES5 days. If you are already familiar with ES6, module-bundling and imports you’d find no problem dealing with Prosemirror anyway.


The conventional way of using an external library was to include the JS file in your index.html in a script tag. This will attach a global namespace/variable for that library which will expose the library’s APIs and methods.

For example: You’ll include <script src=”jquery.js”> in your index.html After that you’ll access all jQuery APIs via window.jQuery or window.$ namespace.

Good News: Things have changed now. Most libraries are now written as ES6/CommonJS Modules which means your global namespace remains pristine.

Bad News: Things have changed now. There are extra steps that you’d need to make before incorporating these libraries into your JS code.


I’m assuming you are either familiar with ES5 JS and / or have a legacy JS codebase. To use Prosemirror in your codebase, you’d have to find a way to export necessary Prosemirror APIs into the global namespace.

Basically, build a ProseMirror.js file that you can use like jquery.js


Create a folder & file structure as below:

1
2
3
4
5
6
7
prosemirror/
       /src
       /src/index.js
     /public
     /public/index.html
       package.json
       rollup.config.js

Since ProseMirror is written using ES6, and we want to use it with plain old ES5 Javascript, we need to transpile ProseMirror library along with its global APIs to ES5.

We are going to do that with Babel & Use Rollup as our module bundler.

Create a package.json file

1
cd  prosemirror

Put the below content into package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
  "name": "setup-prosemirror",

  "dependencies": {
    "prosemirror-example-setup": "^1.0.1",
    "prosemirror-model": "^1.6.4",
    "prosemirror-schema-basic": "^1.0.0",
    "prosemirror-state": "^1.2.2",
    "prosemirror-view": "^1.6.8"
  },
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/preset-env": "^7.2.3",
    "babel-loader": "^8.0.5",
    "rollup": "^1.1.0",
    "rollup-plugin-babel": "^4.3.1",
    "rollup-plugin-commonjs": "^9.2.0",
    "rollup-plugin-node-resolve": "^4.0.0"
  }
}

The package.json file declares all the dependencies to build a final ProseMirror.js file, including all the tools needed.

Now it’s time to use this package.json and install the dependencies. Run:

1
bash$ npm install

After the dependencies are installed, create a rollup.config.js file in the prosemirror directory and put below code in it. This tells Rollup to take our src file from src/index.js and spit out a ProseMirror.js into public/ProseMirror.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import babel from 'rollup-plugin-babel';
import resolve from 'rollup-plugin-node-resolve';
import commonJS from 'rollup-plugin-commonjs'


export default {
  input: './src/index.js',
  output: {
    format: 'iife',
    file: 'public/ProseMirror.js',
    name: 'ProseMirror'
  },
  plugins: [
      babel(),
      resolve(),
      commonJS({
        include: 'node_modules/**'
      })
    ],
};

The configuration is mostly self-explanatory. We are telling Rollup to first convert all fancy ES6 code to ES5, then resolve all dependency libraries from node_modules folder and spit out a final ProseMirror.js as a self executing module format.

Now’s the most important step – Writing the code to import all ProseMirror APIs and exporting them to window namespace.

Put below code into src/index.js

1
2
3
4
5
export { EditorState } from "prosemirror-state";
export { EditorView } from "prosemirror-view";
export { Schema, DOMParser, Node } from "prosemirror-model";
export { schema as basicSchema } from "prosemirror-schema-basic";
export { exampleSetup } from "prosemirror-example-setup";

Without Rollup we would have had to manually attach each API to window ourselves. Like:

1
2
window.ProseMirror = {}
window.ProseMirror.EditorState = EditorState;

But luckily we have a better way. Rollup can just parse this file and do that work us. Just run:

1
bash$ rollup -c

You will see a ProseMirror.js file being created at public/ProseMirror.js

All that is left is to use this compiled JS and initialize a ProseMirror editable area. We’ll include this js file in public/index.html and test out a small demo. Put the below code in public/index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html> <meta charset="utf8" />
<html>
<head>
    <link rel="stylesheet" href="https://prosemirror.net/css/editor.css" />
</head>
<body>
<div id="editor" style="margin-bottom: 23px"></div>
<script src="index.js"></script>
<script>
// window.ProseMirror is active by now.
var plugins = ProseMirror.exampleSetup({ schema: ProseMirror.basicSchema });

var view = new ProseMirror.EditorView(document.querySelector("#editor"), {
    state: ProseMirror.EditorState.create({
        schema: ProseMirror.basicSchema,
        plugins: plugins
    })
});
</script>
</body>
</html>

Open up index.html in a browser and you should see a nice little rich text editor out there!

DISCLAIMER: However convenient this seems, this is a non-scalable way of using ProseMirror. For example anytime you want to use another API from ProseMirror, you’d have to edit src/index.jsto export that API for you. Also, polluting the global namespace is a thing of the past. Moving your project to a good module system (like ES6 Modules) would be more beneficial than the cost involved.

Spring Boot - How to Serve Static Files Without Reloading the Application

The default way of serving static files like JS & CSS via Spring Boot is to put your static folder under /src/main/resources/public. The Internet will give you all kinds of variations of this solution, but almost all of the solutions have a problem.

The static files will be bundled up into the JAR file (that is if you are using the embedded server that comes with Spring). This means you have to reboot the JAR / application everytime you change your CSS or JS. Things could get really painful when you already have a webpack compile process, that will be chained to a JAR compile process.
If you use IntelliJ, there’s a solution to auto-reload your app everytime static files change. This one has its own problems. If you don’t edit static files from your IntelliJ and instead use WebStorm / Sublime / VSCode you need to come back to the IntelliJ window once after editing, so that IntelliJ knows that it should reload static. Fail.

So here’s a solution that worked for me: simply put static resources out of the JAR and write a URL handler that serves static resources from the filesystem. This can be done by hijacking Spring’s default /static url handler and writing your own.

Put your static file in the root folder alongside /src.

1
2
3
4
5
6
7
8
9
myapplication/
           /bin
           /libs
           /src
           /static  ---------> your static folder
                  /css
                      /main.css
                  /js
                      /main.js

Include the following URL handler.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
 * THIS ENDPOINT IS JUST FOR DEV.
 * PRODUCTION MODE SHOULD ALWAYS SERVE STATIC FILES FROM A SEPARATE SERVER
 *
 */
@GetMapping(value = "static/**")
public void serveStatic(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    /*
     * if /static/css/main.css lands here -> path = "/static/css/main.css"
     */
    String path = request.getRequestURI();

    /*
     * with IntelliJ cwd will by default point to "/home/.../application"
     */
    String cwd = Paths.get(".").toAbsolutePath().normalize().toString();
    File file = new File(cwd + path);

    /*
     * If you want you can have your static folder anywhere on your filesystem. Just make sure file object points to the correct path.
     */
    FileInputStream inStream = new FileInputStream(file);
    OutputStream outStream = response.getOutputStream();
    String mimetype = Files.probeContentType(file.toPath());
    response.setContentType(mimetype);

    byte[] buffer = new byte[4096];
    int bytesRead = -1;

    while ((bytesRead = inStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }

    inStream.close();
    outStream.close();
}

With this in place, your spring boot application doesn’t have to be reloaded everytime you change the font-color. Happy Coding!

Implement Decorators in Javascript ES5

There’s an amazing pattern in Python, called function decorators. It’s a set of declarations at the top of a function definition, that slightly enhances how the function behaves without actually polluting the function definition with related logic. I find it a really neat way to define a function and to re-use these enhancements/additional logic across functions.

If you are like me, in love with decorators and now in the wildness of Javascript, missing them – here’s a quick way to implement decorators in JS. My solution here, uses underscore’s compose method. But it’s easy to whip up your own version of compose, if you don’t really want to use underscorejs.

Here’s the short version:

Say, you have a couple of decorators.

One, which logs the return value of the function it decorates.

Two, which makes sure the function is called exactly and only once, no matter how many times it gets invoked.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* Decorator 1 */
var shouldLog = function(original_fn) {
  var decorated_fn = function() {
      var returnVal = original_fn.apply(this, arguments);
      // log the return value
      console.log(returnVal);
      return returnVal;
    }
    return decorated_fn;
}

/* Decorator 2 */
var runOnlyOnce = function(original_fn) {
  var isAlreadyRun = false;
  var decorated_fn = function() {
  // only execute if not already run
  if (!isAlreadyRun) {
          var returnVal = original_fn.apply(this, arguments);
          isAlreadyRun = true;
          return returnVal;
        }
    }
    return decorated_fn;
}

var myFunction = function() {
  // here goes your function definition
}

// now decorate it.
myFunction = _.compose(shouldLog, runOnlyOnce)(myFunction);

Or you can go for another version, if you aren’t really a fan of two liners.

1
2
3
var myLittleFunction = U.compose(shouldLog, runOnlyOnce)(function() {
  // here goes your function definition
});

All done! Now every time you call your function, it passes through the decorators around it.

The logic is pretty straightforward considering you are familiar with higher order functions.

1
2
3
4
5
6
7
8
9
10
11
12
myFunction  = f(x)

shouldLog = g(x) // higher order function where x = some function (f(x))

runOnlyOnce = h(x) // higher order function where x = some function (f(x))

chainedDecorator = _.compose(decoratorFunc1, decoratorFunc2) // h(g(x))

decoratedMyFunction = chainedDecorators(myFunc) // h(g(f(x)))

// to execute function with decorations
decoratedMyFunc(args);

Caution: Be cautious when you write a decorator that modifies the return value / parameters of the function. This could cause potential breakage of other decorators. Be careful when you decorate a method. Make sure decoratedMyFunction is properly bound to the intended context. E.g decoratedMyFunction.bind(MyClass)

HexoPress Now Supports Plain Markdown Files

HexoPress, works primarily on Google Docs. But that’s not enough. There might be certain markdown elements, that you might want to use in your posts, that isn’t there yet in Google Docs – like, codeblocks?

I’ve got news.

HexoPress now understands markdown files the same way it understands Google Doc files. As usual, drop your .md files in your hexopress folder and you are good to go!

This Is Gold

This. Should frame and hang this somewhere in my new place.

A Systematic Approach to Understanding Complex Systems

There is a systematic approach for understanding complicated systems. All it takes is a bit of predicate logic skills and a fair amount of short term memory. Everything else is drawing patterns, connecting dots, thinking it the other way and similar things that our brain already is quite capable of.

To put it in simpler terms, we can just say that to understand a complex system: we’ll need to get a lot of facts about the system and enough space in our head to fit these facts into, so that drawing out meaningful inference out of them becomes an easy thing to do.

So how do you do this effectively? One way is to gain as much facts / data about the system as possible. One simple thumb rule is that if our motive is to change/innovate/rethink the system, we need to know *everything* about the existing system before trying to work on it. So before going into the rethinking mode, gain as much understanding as possible about how the system works currently.

Secondly, when your brain works out logical results out of these dots you’ve accumulated, question them ruthlessly. Drop a *Why* wherever possible. What you are looking for are those scarce little why-s that might lead you to an alternative route, maybe a better route with better outcomes or maybe not.

One effective way to do this is to have a mind-map, or written notes of the decision tree, of all possible questions and answers that comes out of a certain *why*.

The last step is something that you’ll intuitively know–picking a tree from this map of yours.

I’d like to take you through a little tour of how to understand a complex system with example, but I’ll need a lot more time to do that effectively. That can wait. Will do it sometime later.

Hello World!

This is my first blog post @ hexopress.com. JFYI: I made hexopress.com.

Whatever platforms there are now, are great. Except, there is a lock-down of your writings. The platform that you choose, essentially take your writings, packages them into something that the platform can understand for itself and hides them under its pillows, merely extending you with a corner to export them – all the while hoping, you will never need to.

What if the control is inverse?

What if all your posts are somewhere where you decide it to be? What if all these blogging sites are just a conversion layer that treats your files/writings as the primary database and generate a blog out of them?

Octopress is the only one which comes very close to this vision. There’s a tiny little problem though. It’s for hackers. It assumes we will have downright access to a text editor and git, every time we have a great idea that we need to write down – which is actually seldom right.

As for me, most of my “I bloody want to start writing now” moments happen when I am somewhere far far away from my desktop.

But wait, this is an already solved problem.

All these cloud people(Google & Zoho) have been empowering me to write down things, anywhere, on any device – which is exactly what I want now. It’s just I want these blogging softwares to understands what I put in these cloud filesystems.

That’s essentially what HexoPress is. I’m excited about what it will turn out to be.

Go ahead and start writing!