Get the Exact Position and Size of a Window in Windows

Problem

You would like to know the exact pixel position and size of a window in Microsoft Windows.

Solution

Use the very useful utility Sizer. You can download it for free from the page below:

http://www.brianapps.net/sizer/

I downloaded the portable version (download the Zip Package).

Launch sizer.exe from the extracted zip package.

Then right click the title bar of the window of which you would like to know the position and size.

Select the option Resize/reposition from the context menu. Select ‘New entry …’

Now, you can see the width and height as well as the top and left offset for your window:

Remove Duplicates from Array in CoffeeScript

Problem

You have an array in CoffeeScript, which contains equal elements multiple times such as:

[1,1,2,3,3]

You would like to have only unique values in the array. Thus, transform it into:

[1,2,3]

Solution

You can use the following method to accomplish such:

removeDuplicates = (ar) ->
  if ar.length == 0
    return []  
  res = {}
  res[ar[key]] = ar[key] for key in [0..ar.length-1]
  value for key, value of res

alert(removeDuplicates([1,2,3,3,4,4,5]));

References

This solution is based on this approach (with a few minor issues fixed).

Cross-Domain Requests in GWT with JSONP

GWT RPC is built upon AJAX requests and thus is subject to the Same-Origin Policy. However, it is really easy in GWT (as well as in other JavaScript applications) to circumvent this policy using a method called JSON-with-padding (JSONP).

Unfortunately, there are a couple of issues one needs to consider before utilizing JSON-P:

Amount of Data Send from Client to Server

The biggest limitation of JSONP is that it uses GET and not POST requests. Thus, all data send from the client to the server needs to be encoded as URL query parameters such as:

http://myserver.com/myrpctarget?data_from_client=lotsofdatafromclient

These URL parameters can only hold a limited amount of data. I couldn’t find a conclusive upper limit on this, but most sensible suggestions seem to indicate that parameters should be limited to between 2,000 or 4,000 bytes. Please note that many sources here discuss the limit of characters which can be put into a browsers address bar. This limit is not the same as the limit for GET requests triggered from within JS code.

Reliance on GWT RPC

It is a non-trivial (but not impossible – I’ve done it!) endeavor to channel GWT RPC requests through JSONP. Thus, if your application is deeply dependent on GWT RPC, it will probably involve a lot of work to make it JSONP ready. Good news is that if you use the Request Builder API things will be far easier.

Other than these two issues there is really nothing stopping you from writing GWT client applications, which can communicate with multiple servers. I believe that this decoupling from client and server is far more valuable than the added security derived from restricting requests to one domain. After all, the browser is a client application which is by design meant to communicate with many different servers. If you have a choice, consider the two factors above and architect your GWT applications from the very beginning in a way which enables JSONP requests.

Resources

GWT JavaDoc – JsonpRequestBuilder

Wikipedia – JSONP

GWT 2, JSONP and Javascript Overlays with JsonpRequestBuilder

Insert Text at Caret Position in Summernote Editor for Bootstrap

Problem

Using the very useful Summernote Editor component for Bootstrap, you would like to insert some text at the current caret position programmatically.

Solution

The Summernote API does not provide any dedicated methods for inserting text. However, that’s not a problem since we can use the JQuery/native DOM API to insert text into the editor. Thankfully, the content of the Summernote editor is nothing but vanilla HTML/DOM elements. Thus, we can insert text at the current cursor position as follows (if the Summernote editor is focused):

To Insert at the End of the Current Paragraph

$(document.getSelection().anchorNode.parentNode).append(“appended!”);

To Insert at the Current Cursor Position

var selection = document.getSelection();

var cursorPos = selection.anchorOffset;

var oldContent = selection.anchorNode.nodeValue;

var toInsert = “InsertMe!”;

var newContent = oldContent.substring(0, cursorPos) + toInsert + this.substring(cursorPos);

selection.anchorNode.nodeValue = newContent;

Note: You probably will have to work some magic with the document.getSelection() call. The problem is that once you would click a button or trigger the action in some other way, the selection would change. Thus, I save a reference to the document.getSelection() upon every focus and key press event on the editor.

References

MDN – Selection.anchorNode

Stackoverflow – Get caret position in contentEditable div

Stackoverflow – Inserting Text at Cursor Position using JS/JQuery

Stackoverflow – JQuery Plugin for Inserting Text at Caret

 

 

 

CoffeeScript Fat Arrow (=>) explained

Anyone who has worked with JavaScript for anything but a very short time will have come across the problem that the meaning of ‘this’ is often ambiguous at best. CoffeeScript attempts to mitigate this problem somewhat by introducing the Fat Arrow operator (=>). This operator can be used as a replacement for the thin arrow operator (->) used extensively in CoffeeScript for defining functions.

Unfortunately, it is not easy to understand what the fat arrow operator does.I hope the following rules provide some guidance on how to use this operator in CoffeeScript:

Rule 1: You Don’t Need the Fat Arrow If You Don’t Use: class, this, and @

If you are a beginner in JavaScript and/or CoffeeScript, I would recommend keeping your hands of the language constructs ‘this’, ‘class’ and ‘@’. You can implement any application you like without having to use these constructs and it will make your applications more robust and bug free.

Rule 2: Use the Fat Arrow when You Use @ in a Callback Definition in a Method

If you use classes in your code and you want to create a new anonymous function to be passed as a callback (such as to listen to an onclick event or to defined setTimeout function), define this function with the fat arrow operator. This will assure that you still have access to the methods and properties of the class you are working with.

The fat arrow will ‘override’ the default meaning of the @ operator as follows, to assure that ‘this’ refers to what we would expect it:

CoffeeScript

delayedAction = =>  
  alert(@messsage)

setTimeout(delayedAction, 100);

JavaScript

delayedAction = (function(_this) {
  return function() {
    return alert(_this.messsage);
  };
})(this);

setTimeout(delayedAction, 100);

Rule 3: Don’t Use Methods as Callbacks and Avoid the Fat Arrow Operator in All Other Circumstances

There is one more use case for the Fat Arrow operator, which is that it has a special meaning when used for the definition of class methods. This is useful when the methods of a class are to be passed as a callback. I personally don’t think that’s a very useful feature and it’s better to define an anonymous function to handle a callback and then call a method of your class/object from within this callback. Following this rule enables us not having to worry about whether to define a method with a thin or fat arrow – which is otherwise tricky since the right choice here is external to the class we are writing.

More Reading

Karl Seguin – Ten Features I Like About CoffeeScript

Michael Kramer - The Simplified Fat Arrow Guide for CoffeeScript

Azat Mardanov - Understanding Fat Arrows (=>) in CoffeeScript

Giang Nguyen - Coffeescript: Fat arrow vs thin arrow

Embed HTML Code in JavaScript File

Problem

You would like to include HTML code as a String in a JavaScript file.

Solution

Firstly, load the HTML code into a JavaScript variable (e.g. by using jQuery.ajax()).

$.ajax({url: 'http://mydomain.com/htmlfile.html'})

.done(function(html) {

Then apply the following two simple regular expressions on the html code to generate valid JavaScript code.

var safeHtml = html

.replace(/\n/g, "\\n")

.replace(/\"/g, "\\\"")

You can use this String now to build a JavaScript file:

var myScript = 'var html="'+safeHtml+'";';

 

The Dangers of the OK Plateau and How to Overcome Them

I found the following wonderful quote in Daniel Goleman’s Focus: The Hidden Driver of Excellence via Brain Pickings:

Amateurs are content at some point to let their efforts become bottom-up operations. After about fifty hours of training — whether in skiing or driving — people get to that “good-enough” performance level, where they can go through the motions more or less effortlessly. They no longer feel the need for concentrated practice, but are content to coast on what they’ve learned. No matter how much more they practice in this bottom-up mode, their improvement will be negligible.

The experts, in contrast, keep paying attention top-down, intentionally counteracting the brain’s urge to automatize routines. They concentrate actively on those moves they have yet to perfect, on correcting what’s not working in their game, and on refining their mental models of how to play the game, or focusing on the particulars of feedback from a seasoned coach. Those at the top never stop learning: if at any point they start coasting and stop such smart practice, too much of their game becomes bottom-up and their skills plateau.

While this excerpt is centred on sports, it of course applies to many areas in which we might want to develop expertise.

I read another book some time ago, The Little Book of Talent by Daniel Coyle, in which there were some similar ideas. However, in The Little Book of Talent it was added that there are two types of skills: hard skills and soft skills. The former being skills that can easily be advanced through deliberate practice, such as hitting a perfect forehand in tennis, and the latter being skills which are more difficult to practice deliberately, such as developing a strategy to win a tennis match. I think this is a distinction worthy of consideration in the context of the above quote.