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

How to have access to a shell without ssh or telnet using jQuery terminal

If you have, like I do, a virtual server on hosting service, that support cgi but don’t have access to a shell and php have passthru disabled you still can have access to a shell, even if you can’t install anything on that machine – like anyterm.

There is this project, which I did, called jQuery terminal, that emulate a Unix terminal. All you need is interpreter that will execute shell commands.

Lots of hosting services disable php passthru but leave cgi script, so if you have them you can create simple shell like this one:

UPDATE: If you don’t want to code it yourself (or look at working solution), you can check my project LEASH – Browser Shell.

echo -en "Content-Type: text/plain\r\n\r\n"
query=$(/usr/bin/python -c "import urllib; print urllib.unquote_plus('$QUERY_STRING')")
eval $query 2>&1

I use python subprocess to decode QUERY_STRING. Probably it can be done using some Unix tools.

On my server I use Python CGI script like this one:.

import cgi
import subprocess as sub

    from json import dumps as json_serialize
except ImportError:
    def json_serialize(obj):
        result = ''
        t = type(obj)
        if t == types.StringType:
            result += '"%s"' % obj.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n')
        elif t == types.NoneType:
            result += 'null'
        elif t == types.IntType or t == types.FloatType:
            result += str(obj)
        elif t == types.LongType:
            result += str(int(obj))
        elif t == types.TupleType:
            result += '[' + ','.join(map(json_serialize, list(obj))) + ']'
        elif t == types.ListType:
            result += '[' + ','.join(map(json_serialize, obj)) + ']'
        elif t == types.DictType:
            array = ['"%s":%s' % (k,json_serialize(v)) for k,v in obj.iteritems()]
            result += '{' + ','.join(array) + '}'
            result += '"unknown type - ' + type(obj).__name__ + '"'
        return result

class Singleton(object):
    __single = None
    def __init__(self):
        Singleton.__single = self

    def __new__(cls):
        if Singleton.__single:
            return Singleton.__single
            return super(Singleton, cls).__new__(cls)

class Form(Singleton):
    def __init__(self):
        self.form = cgi.FieldStorage()

    def __getitem__(self, name):
        return self.form.getvalue(name)

def execv(command, path):
    command = 'cd %s && %s && pwd 1>&2' % (path, command)
    proc = sub.Popen(['/bin/bash', '-c', command],
                     stdout=sub.PIPE, stderr=sub.PIPE)
    stderr =[:-1]
    stdout =[:-1]
    if not os.path.exists(stderr):
        raise Exception(stdout, stderr)
    return {
        "cwd": stderr,
        "stdout": re.sub('.\x08', '', stdout)

if __name__ == '__main__':
    print "Content-Type: text/plain"
    form = Form()
    if token() == form['token']:
        response = {}
            response['result'] = execv(form['command'], form['path'])
        except Exception, e:
            response['error'] = e.args[1]
            response['result'] = {'stdout': e.args[0], 'cwd': form['path']}
            response['error'] = None
        response = {'error': 'You are not authorized', 'result': None}

You have enabled passthru in php you can write your shell in php.

Now when you have access to a shell you need to setup interface using jQuery terminal.

<html xmlns="">
    <meta charset="utf-8" />
    <script src=""></script>
    <script src="terminal/js/jquery.mousewheel-min.js"></script>
    <script src="terminal/js/jquery.terminal.js"></script>
    <link href="terminal/css/jquery.terminal.css" rel="stylesheet"/>
    .terminal a.ui-slider-handle:focus { outline: none; }
    body { margin: 0; padding: 0; }
    html { background-color: #000; }
    .clear { clear: both; }
    /* This works only in Safari and Google Chrome */
    @media screen and (-webkit-min-device-pixel-ratio:0) {
        .terminal, .terminal .terminal-output, .terminal .terminal-output div,
        .terminal .terminal-output div div, .cmd, .terminal .cmd span, .terminal .cmd div {
            font-weight: bold;
$(function() {
    var pwd, last_dir, home_dir;
    var terminal = $('#shell').terminal(function(command, term) {
        if (command.replace(/^ *(.*) *$/, '$1') == '-') {
            pwd = last_dir;
        $.post("/cgi-bin/", {
            token: term.token(),
            command: command.replace(/(\\)?~/, function($0,$1) {
                return $1 ? $0 : home_dir;
            path: pwd
        }, function(response) {
            pwd = response.result.cwd;
    }, {
        login: function(user, password, authenticate) {
            $.post("/cgi-bin/", {
                user: user,
                password: password
            }, function(token) {
                if (token) {
                    home_dir = pwd = last_dir = '/home/ + user;
        prompt: function(callback) {
            var username = terminal.login_name();
            var re = new RegExp("^" + '/home/' + username);
            var username = '[[;#44D544;]' + username + ']';
            var path = '[[;#5555FF;]' + pwd.replace(re, '~') + ']';
            callback(username + '[[;#989898;]:]' + path + '[[;#989898;]$] ');
        name: 'shell'
        overflow: 'auto'

    $(window).resize(function() {
       terminal.css('height', $(window).height()-20);

  <div id="shell"></div>

, ,

1 Comment

My Poster for Libre Graphics Meeting

Libre Graphics Meeting – Free Graphic Design Conference for Free Libre and Open Source Software

Libre Graphics Meeting - Free Graphic Design Conference for Open Source Software

My Poster to Libre Graphics Meeting Conference – conference about open source software use to create graphics of any kind. you can also download pdf version

Help make this event happen – donate

Visit official site for the conference

Follow LGM on twitter

Do you want to be on a poster? – Become a sponsor

See promoting Video from Last Year

, ,

1 Comment

Switching between buffers with the same major mode in Emacs

Below are functions that can be used to switch to next or previus buffer in the same major mode

(defun buffer-same-mode (change-buffer-fun)
  (let ((current-mode major-mode)
        (next-mode nil))
    (while (not (eq next-mode current-mode))
      (funcall change-buffer-fun)
      (setq next-mode major-mode))))

(defun previous-buffer-same-mode ()
  (buffer-same-mode #'previous-buffer))

(defun next-buffer-same-mode ()
  (buffer-same-mode #'next-buffer))

In my init file I have bind those functions to CTRL+TAB and CTRL+ALT+TAB which was not set by default.

(global-set-key [C-M-tab] 'previous-buffer-same-mode)
(global-set-key [C-tab] 'next-buffer-same-mode)


Leave a comment

Faster buffer bookmarking in Emacs

I wanted to speed up jumping in the same buffer so I have written this bookmarking utility (Similar to built-in registers) and put it in my .emacs file.

(defvar bookmark-markers '())

(defun bookmark (bookmark)
   "Store current position for this buffer in 
    bookmar-markers a-list"
   (interactive "nBookmark: ")
   (let* ((buffer (current-buffer))
           (let ((pair (assoc buffer bookmark-markers)))
             (if (eq pair nil)
                 (let ((new-pair (cons buffer '())))
                     (setq bookmark-markers
                           (append bookmark-markers
                                   (list new-pair)))
     (let ((pair (assoc bookmark bookmarks)))
       (if (eq pair nil)
           (setf (cdr bookmarks)
                 (append (cdr bookmarks)
                         (list (cons bookmark (point)))))
         (setf (cdr pair) (point))))))

(defun jump-to-bookmark (bookmark)
  "Jump to previously stored bookmark position"
  (interactive "nJump To: ")
  (let ((pair-bookmars (assoc (current-buffer) bookmark-markers)))
    (if (not (eq pair-bookmars nil))
        (let ((pair-point (assoc bookmark (cdr pair-bookmars))))
          (if (not (eq pair-point nil))
              (goto-char (cdr pair-point)))))))

(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)))))

(dolist (i (range 9))
    (global-set-key (read-kbd-macro (concat "C-c "
                                            (number-to-string i)))
                    ;; emacs lisp have no closures
                    (lexical-let ((i i)) 
                      (lambda ()
                        (jump-to-bookmark i)))))

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

Above code define 2 functions bookmark bind to C-c 0 and function jump-to-bookmark this function create a bookmark, for currect position in a buffer, and assing it to the number (passed as argument or from minubuffer, if run interactively). You have 9 keyboard binding for keys from C-c 1 to C-c 9.

You can use it go to specific location and type C-c 0 1 RET go to another location and type C-c 0 2 RET and now you can jump to locations with C-c 1 or C-c 2.

Every buffer will have they own bookmarks.


Leave a comment

Matrix manipulation in scheme

Here’s the code I wrote for matrix manipulation in scheme. It use lists.

Procedure that creates new square identity matrix:

(define (make-matrix n)
  (let outter ((i n) (result '()))
    (if (= i 0)
        (outter (- i 1) 
                 (let inner ((j n) (row '()))
                   (if (= j 0)
                       (inner (- j 1) (cons (if (= i j) 1 0) row))))

Procedure that return nth element of the list, which is the same as nth row of the matrix:

(define (nth list n)
  (let iter ((n n) (result list))
    (if (= n 0)
        (car result)
        (iter (- n 1)
              (cdr result)))))

(define matrix-row nth)

Procedure that return nth column of the matrix:

(define (matrix-col M n)
  (let iter ((i (length M)) (result '()))
    (if (= i 0)
        (iter (- i 1)
              (cons (nth (nth M (- i 1)) n) result)))))

Procedure for multiplication of two matrices:

(define (matrix-mul N M)
  (let rows ((i (length N)) (result '()))
    (if (= i 0)
        (rows (- i 1)
               (let cols ((j (length (car M))) (row '()))
                 (if (= j 0)
                      (- j 1)
                      (cons (reduce + (map *
                                           (matrix-row N (- i 1))
                                           (matrix-col M (- j 1))))

For above procedure you will need reduce procedure:

(define (reduce fun lst)
  (let iter ((result (car lst)) (lst (cdr lst)))
    (if (null? lst)
        (iter (fun result (car lst)) (cdr lst)))))

Procedure for multiplication of vector and matrix:

(define (matrix-vector-mul v M)
  (car (matrix-mul (list v) M)))

Procedure for transpose the matrix:

(define (matrix-transpose M)
  (if (null? (car M))
      (cons (map car M)
            (matrix-transpose (map cdr M)))))

Tail recursive procedure for transpose the matrix:

(define (matrix-transpose M)
  (let iter ((M M) (result '()))
    (if (null? (car M))
        (iter (map cdr M) (append result (list (map car M)))))))

Procedure that calculate the sum of two matrices:

(define (matrix-sum N M)
  (let iter ((N N) (M M) (result '()))
    (if (or (null? N) (null? M))
        (reverse result)
        (iter (cdr N) 
              (cdr M)
              (cons (map + (car N) (car M)) result)))))

Shorter version of the above:

(define (matrix-sum N M)
  (map (lambda (nrow mrow) (map + nrow mrow)) N M))


You can use those procedures like this:

(define M1 '((1 2 3) (2 3 4) (3 2 1)))
(define M2 (make-matrix 3))

(write (matrix-mul M1 M2))
(write (matrix-mul M1 '((2 3 1) (1 2 1) (1 3 1))))
(write (matrix-sum M1 M2))
(write (matrix-vector-mul '(2 3 1) M1)


Leave a comment

666 the number of the beast tweets on smashing magazine

I spot number of the beast tweets on smashing magazine article “Desktop Wallpaper Calendar: April 2011”

666 the number of the beast tweets

Leave a comment


Get every new post delivered to your Inbox.

%d bloggers like this: