Add methods to Number object in JavaScript

In JavaScript everything is an object, even functions and numbers, and all objects even functions are first class citizens (which allow functional programming).

So this mean that you can call methods over numbers, and you can add new methods using Number.prototype. Here is example of range functions similar to that from Python, but bit different. (Python one return number from n to m – or from 0 to n – but this one return n numbers (n is this) starting from number passed as argument)

Number.prototype.range = function(n, result) {
    result = result || [];
    n = typeof n === 'undefined' ? 0 : n;
    if (this <= 0) {
        return result.reverse();
    } else {
        return, n, result.concat([this-1+n]));

And you can call this function/method using:


It will return array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

Note that there are two dots, it’s because when you use one it’s interpret as float number and thorw exception "SyntaxError: Unexpected token ILLEGAL" because it wait for a digit as next character.

Using this you can write factorial using

10..range(1).reduce(function(a, b) { return a*b; });

reduce function was added to Array.prototype in ECMAScript 5, You can check what browsers support them in this page.

You can wrap that code with a function and you can add it as Number prototype

Number.prototype.factorial = function() {
    return this.range(1).reduce(function(a, b) { return a*b; });

You can call it as:


Here is example of times function (similar to that from Ruby)

Number.prototype.times = function(fn, self) {
    return this.range().forEach(fn, self);

You can use this function using:

10..times(function(i) { console.log(i); });

Leave a comment

Working with SVG in jQuery

I recently notice that if you create element like a circle in SVG (inline SVG embedded into HTML), using inspector/firebug or jQuery, your circle is not visible on SVG until you refresh the SVG, I found a hack to force refresh of the SVG, I just get text of the SVG and insert it again into the DOM, and all elements that were not visible like circle mention before will be rendered.

Here is referesh function, as jQuery plugin

$.fn.xml = function() {
    return (new XMLSerializer()).serializeToString(this[0]);

$.fn.DOMRefresh = function() {
    return $($(this.xml()).replaceAll(this));

Those plugins should work with every XML embeded into HTML not only SVG. Don’t look very nice but it work, but I found a better way fix jQuery to work with SVG. I found that when I use function document.createElementNS instead of document.createElement elements added to inline SVG using for instance appendChild function everything work fine. So only thing that need to be done for jQuery to work with inline SVG is to replace this function if element is SVG. First I wrote method in jQuery object that test if element is SVG element, there are only three elements that have the same name in HTML and SVG is a, script, style and title tags so I didn’t put them in.

isSVGElement: function( o ) {
        if (o instanceof SVGElement) {
            return true;
        } else {
            if (typeof o === 'string') {
                return $.inArray(o, ['altGlyph', 'altGlyphDef',
                                     'altGlyphItem', 'animate',
                                     'animateColor', 'animateMotion',
                                     'animateTransform', 'circle',
                                     'clipPath', 'color-profile',
                                     'cursor', 'defs', 'desc', 'ellipse',
                                     'feBlend', 'feColorMatrix',
                                     'feComposite', 'feConvolveMatrix',
                                     'feDistantLight', 'feFlood',
                                     'feFuncA', 'feFuncB', 'feFuncG',
                                     'feFuncR', 'feGaussianBlur',
                                     'feImage', 'feMerge', 'feMergeNode',
                                     'feMorphology', 'feOffset',
                                     'feSpecularLighting', 'feSpotLight',
                                     'feTile', 'feTurbulence', 'filter',
                                     'font', 'font-face',
                                     'font-face-name', 'font-face-src',
                                     'font-face-uri', 'foreignObject',
                                     'g', 'glyph', 'glyphRef', 'hkern',
                                     'image', 'line', 'linearGradient',
                                     'marker', 'mask', 'metadata',
                                     'missing-glyph', 'mpath', 'path',
                                     'pattern', 'polygon', 'polyline',
                                     'radialGradient', 'rect',
                                     'set', 'stop', 'svg',
                                     'switch', 'symbol', 'text',
                                     'textPath', 'tref',
                                     'tspan', 'use', 'view',
                                     'vkern']) !== -1;

I get the list of elements from Mozilla MDN.

I added this method to main jQuery.extend({ that add methods to jQuery object. Next thing is to replace createElement with createElementNS, there are only 2 places with this in parseHTML (in the same jQuery.extend) and createSafeFragment function, only one is responsible for inserting elements – parseHTML. Below is the code for that function.

	parseHTML: function( data, context, keepScripts ) {
		if ( !data || typeof data !== "string" ) {
			return null;
		if ( typeof context === "boolean" ) {
			keepScripts = context;
			context = false;
		context = context || document;

		var parsed = rsingleTag.exec( data ),
			scripts = !keepScripts && [];

		// Single tag
		if ( parsed ) {
			if ( jQuery.isSVGElement( parsed[1] ) ) {
				return [ context.createElementNS(
					parsed[1]) ];
			} else {
				return [ context.createElement( parsed[1] ) ];

		parsed = jQuery.buildFragment( [ data ], context, scripts );
		if ( scripts ) {
			jQuery( scripts ).remove();
		return jQuery.merge( [], parsed.childNodes );

Unfortunetnly not all manupulation methods that create new elements will work but it’s better then refresh hack. The stuff that don’t work is when you create more then one element from a string or if you put some attributes. In this case jQuery use document fragments and innerHTML to create the DOM. If we will want to fix that too we will need to write a parser that will call createElementNS.

You can also include those function after you load jQuery so original code will not be changed.

The other way is to use document.createElementNS and element.setAttributeNS that need to be used if you want to add xlink:href attribute (it use namespace).


Leave a comment

Image color picker in javascript that work without canvas in every browser

If you want to create color picker from image in javascript you probably will use canvas, but what if you need it work in IE as I needed. You can use some server side help to fetch pixels data from the server. I use php for that and GD library. The code is below.

cross-browser color picker

Server side code that return json pixel data


function rgb($color) {
    $result[] = ($color >> 16) & 0xFF;
    $result[] = ($color >> 8) & 0xFF;
    $result[] = $color & 0xFF;
    return $result;

function imagecreatefrom($filename) {
    $path = pathinfo($filename);
    switch($path['extension']) {
        case 'png':
            return imagecreatefrompng($filename);
        case 'jpg':
            return imagecreatefromjpeg($filename);
        case 'gif':
            return imagecreatefromgif($filename);
            return null;

function getImageData($filename) {
    list($width, $height) = getimagesize($filename);
    $image = imagecreatefrom($filename);
    $image_data = array();
    for ($y = 0; $y < $height; ++$y) {
        $row = array();
        for ($x = 0; $x < $width; ++$x) {
            $row[] = rgb(imagecolorat($image, $x, $y));
        $image_data[] = $row;
    return $image_data;

if (isset($_GET['filename'])) {
    $filename = $_GET['filename'];
    if (file_exists($filename)) {
        $result = array(
            'error' => null,
            'result' => getImageData($filename)
    } else {
        $result = array(
            'error' => "The file '$filename' don't exist",
            'result' => null
} else {
    $result = array(
        'error' => "You need to put filename",
        'result' => null
header('Content-Type: application/json');
echo json_encode($result);


Then you can fetch the data using ajax and add get invidial pixels on mousemove

    var img = $('img');
    $.getJSON('image_data.php', {filename: img.attr('src')}, function(data) {
        if (data.error) {
        } else {
            $('.eyedropper').click(function() {
                picker = true;
                return false;
            img.mousemove(function(e) {
                if (picker) {
                    var x = Math.round(e.pageX - offset.left);
                    var y = Math.round(e.pageY -;
                    if (x >= 0) {
            }).click(function(e) {
                picker = false;

Now all you need to have is element with class eyedropper like a link in your html:

<a href="#" class="eyedropper">pick the color</a>

, ,


Mastering Emacs – Search inside minibufer

This is by far best feature in Emacs that you can use interactive search inside Minibuffer. If you want to find a function that you don’t know exact name, I do this a lot – who will remember function names in Emacs, you can use:

C-h f C-s

And search for functions. How cool is that? Almost all functions that have completion inside minibuffer work with search like

  • C-x b C-s – search for buffer to switch
  • C-h <KEY> C-s – search for help

When I switch to Emacs 24, I found that M-x C-s don’t work. So you can’t search for interactive function to execute. But you can get it back. As describe by this Emacs Bug Ticket by putting this to you .emacs file.

(defun read-extended-command ()
  "Read command name to invoke in `execute-extended-command'."
      (lambda ()
        (set (make-local-variable 'minibuffer-default-add-function)
             (lambda ()
               ;; Get a command name at point in the original buffer
               ;; to propose it after M-n.
               (let ((def (with-current-buffer
                              (window-buffer (minibuffer-selected-window))
                            (and (commandp (function-called-at-point))
                                 (format "%S" (function-called-at-point)))))
                     (all (sort (minibuffer-default-add-completions)
                                (lambda (a b) (string< a b)))))
                 (if def
                     (cons def (delete def all))
    ;; Read a string, completing from and restricting to the set of
    ;; all defined commands.  Don't provide any initial input.
    ;; Save the command read on the extended-command history list.
     (concat (cond
	      ((eq current-prefix-arg '-) "- ")
	      ((and (consp current-prefix-arg)
		    (eq (car current-prefix-arg) 4)) "C-u ")
	      ((and (consp current-prefix-arg)
		    (integerp (car current-prefix-arg)))
	       (format "%d " (car current-prefix-arg)))
	      ((integerp current-prefix-arg)
	       (format "%d " current-prefix-arg)))
	     ;; This isn't strictly correct if `execute-extended-command'
	     ;; is bound to anything else (e.g. [menu]).
	     ;; It could use (key-description (this-single-command-keys)),
	     ;; but actually a prompt other than "M-x" would be confusing,
	     ;; because "M-x" is a well-known prompt to read a command
	     ;; and it serves as a shorthand for "Extended command: ".
	     "M-x ")
     obarray 'commandp t nil 'extended-command-history)))

And tell me, why you will ever need Ido-mode

One note about that, when you use one interactive function inside another one you will need to call C-g twice to exit minibuffer

1 Comment

Faster Emacs Window Switching Inside a Frame

I needed something to speed up my work when I have few windows, I was looking at switch-window.el, but it kind of silly that the content of the window disappear. So I’ve written this simple 2 functions which act similar to my other sollution Faster buffer bookmarking in Emacs. But you mark window to which you want to jump.

It set Keyboard C-c C-0 for mark and C-C C-<1-9> to jump.

(setq window-alist '())

(defun mark-window (number)
  "Give current window a number to select it later using `switch-to-number-window'"
  (interactive "nNumber Your Window: ")
  (let ((pair (assoc number window-alist))
        (window (get-buffer-window)))
    (if pair
        (setf (cdr pair) window)
      (add-to-list 'window-alist (cons number window)))))

(defun switch-to-number-window (number)
  "Jump to the window  marked with a `mark-window' function"
  (interactive "nNumber Your Window: ")
  (let ((pair (assoc number window-alist)))
    (if pair
        (select-window (cdr pair))
      (message "Invalid Number"))))

;; create 9 keyboard shortcuts using closure (forced using lexical-let)
(dolist (i (map #'1+ (range 9)))
    (global-set-key (read-kbd-macro (concat "C-c C-"
                                            (number-to-string i)))
                    (lexical-let ((i i))
                      (lambda ()
                        (switch-to-number-window i)))))

(global-set-key (kbd "C-c C-0") 'mark-window)

It use range helper function (same as in python)

(defun range (n &optional list)
  "function return list of numbers from 1 to n"
  (if (eq n 0)
    (let ((n (- n 1)))
      (range n (cons n list)))))

EDIT: I just found windmove commands which are much better.

, ,

Leave a comment

How To Add Translation Feature To Twitter

I don’t know about you but, I follow few peple that sometimes tweet in different language then English. And English is the only foreign language I know. So if I want to see what they tweet about sometimes I use google translate to read the content.

I always thought that it will be nice feature for Twitter to have translate button, so I created one, using WebSockets and Ruby.

So how I did this, first I downloaded websockets ruby library from github web-socket-ruby, I already had translation script written in Ruby that use google translate, so I added websocket server to it.


require 'net/http'
require 'uri'
require 'optparse'
require 'json'
require 'socket'
require 'web_socket'

class NotConnectedException < Exception

def server(port, domains)
  server =
    :accepted_domains => domains,
    :port => port)
  puts("Server is running at port %d" % server.port) do |ws|
    puts("Connection accepted")
    puts("Path: #{ws.path}, Origin: #{ws.origin}")
    if ws.path == "/translate"
      while data = ws.receive()
        printf("Received: %p\n", data)
        data = JSON.parse(data)
        response = translate(data['text'], nil, data['to_lang']).join("\n")
        printf("Sent: %p\n", response)
      ws.handshake("404 Not Found")
    puts("Connection closed")

def escape(o)
  o.gsub(/([^ a-zA-Z0-9_.-]+)/n) {
    '%' + $1.unpack('H2' * $1.size).join('%').upcase
  }.tr(' ', '+')

def translate(text, from=nil, to=nil, cookie=nil)
  url = URI.parse("")
  query = "?hl=en&client=t&text=#{escape(text)}&multires=1&otf=1&pc=0&sc=1&ie=UTF-8&oe=UTF-8"
  query += "&sl=" + (from ? from : 'auto')
  if to
    query += "&tl=#{to}"
    http =
    res = http.get(url.path + query)
    res.response['content-type'] =~ /charset=(.*)/
    charset = $1
    JSON.parse(res.body.gsub(/,{2,}/, ',').gsub(/,\]/, ']'))[0].map {|i|
      # google sometimes put spaces around numbers
      i[0].gsub(/\{ *([0-9]) *\}/, '{\1}')
  rescue NoMethodError
    raise NotConnectedException
  rescue SocketError
    raise NotConnectedException

def msg(str, type='info')
  system("zenity --#{type} --title='translation' --text='#{str}'")

params = ARGV.getopts('i:o:gcsp:')

def error(msg, gui=false)
  if gui
    msg(msg, 'error')
    puts msg

def usage()
  puts "usage:"
  puts "translate [-i <INPUT LANG>] -o <OUTPUT LANG> [MORE OPTIONS]"
  puts "-g - show zenity dialog"
  puts "-c - get input from clipboard"
  puts "-s - run as server"
  puts "-p - server port"

  if params['s']
       server(params['p'] ? params['p'].to_i() : 8080, '')
     rescue Interrupt
       puts "Server Exit"
    if params['c']
      input = `xclip -o -sel clip`
      input =
    translation = translate(input, params['i'], params['o'])
    if params['g']
      msg(translation.join(". "))
        if sentence != ''
          puts sentence
rescue JSON::ParserError => e
  error("Response Error: " + e.message, params['g'])
rescue NotConnectedException
  error("sorry but it seems that your internet connection is down", params['g'])

Then I created this bookmarklet. (I notice that profile page use jQuery.noConflict() so I can’t access it from bookmarklet. So here is updated code that insert jQuery script again – in use continuation to block execution of the script until jQuery is loaded). To use bookmarklet just copy code below and insert into url address bar when twitter tab is active

javascript:(function(continuation) {
    function attr(elem, key, value) {
        elem.setAttribute(document.createAttribute(key, value));
    var script = (function() {
        var head = document.getElementsByTagName('head')[0];
        return function(src) {
            var script = document.createElement('script');
            script.setAttribute('src', src);
            script.setAttribute('type', 'text/javascript');
            script.setAttribute('async', 'false');
            return script;
    var interval = 100;
    setTimeout(function() {
        if (jQuery) {
        } else {
            setTimeout(arguments.callee, interval);
    }, interval);
})(function($) {
    function translator(fun, lang) {
        var socket = new WebSocket("ws://localhost:8080/translate");
        socket.onopen = function() {
            console.log("Socket has been opened!");
        socket.onclose = function() {
        return fun(function(text, respond) {
            socket.onmessage = function(msg) {
            var data = JSON.stringify({to_lang: lang, text: text});
    var translate_tweet = translator(function(translate) {
        return function(content) {
            var tweet_container = content.find('.js-tweet-text');
            var tweet = tweet_container.html();
  'original', tweet);
            var links = [];
            var i = 0;
            tweet = tweet.replace(/<a[^>]+>[^<]+<\/a>|<a[^>]+><s>(#|@)<\/s><b>[^<]+<\/b><\/a>/g, function(link) {
                return '{' + i++ + '}';
            translate(tweet, function(result) {
                for (var i=links.length; i--;) {
                    result = result.replace('{' + i + '}', links[i]);
                var actions = content.find('.tweet-actions');
                if (actions.find('.action-orig-container').length == 0) {
                    actions.append('<li class="action-orig-container"><a href="#">Original</a></li>');
    }, prompt('Select Language: af - afrikaans, sk - albánskej, ar - عربي, be - Беларускі, bg - Български, zh - 荃湾, zh - 太阳, hr - Hrvatski, cs - Český, da - Danske, et - Eesti, tl - filipiński, fi - Suomi, fr - Français, gl - galijski, el - Ελληνικά, iw - עברית, hi - हिन्दी, es - Español, nl - Nederlands, id - indonezyjski, ga - Gaeilge, is - Íslenska, ja - 日本語, yi - ייִדיש, ca - Català, ko - 한국의, lt - Lietuvos, lv - Latvijas, mk - Македонски, ms - Melayu, mt - Malti, de - Deutsch, no - Norsk, fa - فارسی, pl - polski, ru - Русский, ro - Română, sr - Српски, sk - Slovenský, sl - Slovenski, sw - Swahili, sv - Svenska, th - ภาษาไทย, tr - Türk, uk - Український, cy - walijski, hu - Magyar, vi - Việt, it - Italiano'));
    $('.content').unbind('mouseover').live('mouseover', function() {
        var $this = $(this);
        if ($this.find('.action-trans-container').length == 0) {
                after('<li class="action-trans-container"><a href="#">Translate</a></li>');
    $('.action-orig-container').unbind('onclick').live('click', function() {
        var content = $(this).parents('.content');
        return false;
    $('.action-trans-container').unbind('onclick').live('click', function() {
        return false;

CODE LICENSE: you can use the code for whatever purpose you like it’s realeas on Sharing Agreement.

, ,


ERC notifications on channels where there was activity after some inactivity

I need to monitor few IRC channels and I use Emacs so I write simple elisp function that I append to erc-insert-pre-hook and it notify me when there is some activity on those channels. I made this mainly because I what to know if someone visit #openclipart channel (because people where visiting ask question and leave after few minutes, there is no much activity on this channel)

(setq inactivity-buffer-alist '(("#openclipart" (inactivity . 900))
                                ("#hackerrank" (inactivity . 900))
                                ("#aiki" (inactivity . 900))))

(defun channel-activity (string &rest ignore)
  "notification when there is activity on a erc channel after inactivity"
  (let* ((buffer (buffer-name))
         (buffer-alist-pair (assoc buffer inactivity-buffer-alist))
         (buffer-alist (cdr buffer-alist-pair))
         (current-time (current-time)))
    (if (not (null buffer-alist))
        (let ((last-time-pair (assoc 'last-time buffer-alist))
              (inactivity (cdr (assoc 'inactivity buffer-alist))))
          (if (not (and (string-match "^\\*\\*\\*" string)
                        (string-match "[freenode-info]" string)))
                (if (or (null last-time-pair)
                        (> (float-time (time-subtract current-time
                                                      (cdr last-time-pair)))
                    (async-exec-command "mpg123 -q /home/kuba/Pobrane/beep-6.mp3"))
                (if (null last-time-pair)
                    (setf (cdr buffer-alist-pair)
                          (append buffer-alist
                                  (list (cons 'last-time current-time))))
                  (setf (cdr last-time-pair) current-time))))))))

(add-hook 'erc-insert-pre-hook 'channel-activity)

You can add your channels to inactivity-buffer-alist along with time of inactivity (in miliseconds)

The function I use for notification is play sound using (async-exec-command "mpg123 -q /home/kuba/Pobrane/beep-6.mp3") – normal shell command was stoping execution of Emacs for few seconds

The code for this function is as follow

(defun async-exec-command (command &rest success)
  (let* ((buffer-name (generate-new-buffer-name "**shell**"))
         (buffer (get-buffer-create buffer-name))
         (process (apply #'start-process
                         (append (list buffer-name buffer)
                                 (split-string command " ")))))
    (lexical-let ((buffer buffer) (success (car success)) (command command))
      (set-process-sentinel process
                            (if success (lambda (process str)
                                          (if (string= str "finished\n")
                                                (set-buffer buffer)
                                                (let ((content (buffer-string)))
                                                  (kill-buffer buffer)
                                                  (funcall success content)))))
                              (lambda (proces str)
                                (kill-buffer buffer)))))
    (concat "execute: " command)))

, , ,

Leave a comment


Get every new post delivered to your Inbox.

%d bloggers like this: