Friday, December 23, 2011

Bash script can tell its location

You can get the path of the directory in which a bash script is located FROM that bash script.

Read more about this problem on stackoverflow.

Tuesday, December 20, 2011

Print out more than 20 items in mongodb shell

When you're listing a large dataset in the shell you'll only see 20 items by default and a 'has more' text indicating that there are more.
If you want to change this limit you can use

DBQuery.shellBatchSize = 300

in the shell.

Saturday, December 17, 2011

Loading CDN hosted jQuery with local fallback

I found this piece of art in html5boilerplate.
It tries to load jQuery from a CDN and if it fails for whatever reason it tries a local one.

Friday, December 9, 2011

Creating a custom google maps marker with canvas

Generating a custom marker with canvas is handy when you want to change the marker size/color dynamically.

The following code snippet contains a 'createMarker' function that creates a canvas, draws the marker graphics and returns back the Data URL encoded version of that canvas which can be used as an input at the marker creation.

See the example below.

Thursday, November 3, 2011

String trimming in Javascript

Here is a simple trim function to remove leading and trailing whitespaces.

function trim(s) {
return s.replace(/^\s*|\s*$/g, '');

and in CoffeeScript
trim = (s) ->
s.replace /^\s*|\s*$/g, ''

You can check Steven Levithan's collection of trim functions.

Saturday, October 29, 2011

'Taglist: Exuberant ctags ( not found in PATH. Plugin is not loaded.' error in MacVim (Janus)

After launching MacVim you may get this annoying error message:
'Taglist: Exuberant ctags ( not found in PATH. Plugin is not loaded.'

To remove this you have to install ctags which you can download from
After you unziped it, you have to set the Tlist_Ctags_Cmd variable in the .vimrc file to point to the ctags folder.

let Tlist_Ctags_Cmd = '/usr/local/bin/ctags'

After that you have to restart vim and the message should not pop up again.

Tuesday, October 25, 2011

Launching MacVim from Command line

Put this into your .profile or .zshrc file
function mvim { /Applications/ -g $*; } 

Then you can use 'mvim' in the command line.

The full explanation is in the MacVim Google Groups

Tuesday, September 27, 2011

Simulating slow network connection in OSX

sudo ipfw pipe 1 config bw 16Kbit/s delay 350ms

sudo ipfw add 1 pipe 1 src-port 80
sudo ipfw add 2 pipe 1 dst-port 80

sudo ipfw delete 1
sudo ipfw delete 2

sudo ipfw pipe 1 delete

Wednesday, September 21, 2011

Disable spotlight

Disable Spotlight
sudo mdutil -a -i off

Enable Spotlight
sudo mdutil -a -i on

Tuesday, September 20, 2011

Tapping on <label> in Mobile Safari

Tapping on <label> does not auto-focus linked in Mobile Safari but If we add an empty function as clickhandler it works fine.

<input type="checkbox" id="test" name="test">
<label for="test" id="test_label">This is the label</label>
document.getElementById("test_label").onclick = function () {};

This is the releated Stackoverflow discussion.

Thursday, September 8, 2011

Checkbox/Radio button size on Android Safari

You cannot change checkbox/radio button width/height on Android in Safari because it is tied to the OS.

But since the default ones are so tiny that you may need bigger buttons.
Here is a simple trick:

input[type=checkbox] {
-webkit-transform: scale(2,2);

Please note that if you set up values bigger than ~2 then the yellow outline will look weird.

Friday, July 29, 2011

Get links from a page with bash

Get anchor elements from a webpage can be done with

curl URL 2>&1 | grep -o -E 'href="([^"#]+)"' | cut -d'"' -f2

where you replace URL with your choice, just like here:
curl 2>&1 | grep -o -E 'href="([^"#]+)"' | cut -d'"' -f2

Tuesday, July 26, 2011

Switching back to the previous application with AppleScript

If you want to simulate cmd + tab with AppleScript, here it is

tell application "System Events"
tell process "finder"
keystroke tab using {command down}
end tell
end tell

You can use the same thing in bash

echo 'tell application "System Events"
tell process "finder"
keystroke tab using {command down}
end tell
end tell' | osascript

Thursday, July 14, 2011

Show Git Commits By Author

It is as simply as
git log --author=<PATTERN>

for example

git log --author=viktor

Tuesday, July 5, 2011

Resize and position windows with AppleScript

-- get the dimensions of the desktop, set up few variables
tell application "Finder"
set displayAreaDimensions to bounds of window of desktop
set x1 to item 1 of displayAreaDimensions
set y1 to item 2 of displayAreaDimensions
set x2 to item 3 of displayAreaDimensions
set y2 to item 4 of displayAreaDimensions
end tell

set width to x2 - x1
set height to y2 - y1

-- positioning iTunes, make it fullscreen
tell application "iTunes"
set the bounds of the first window to {x1, y1, x2, y2}
end tell

-- positioning Safari, halfwidth on the right
tell application "Safari"
set the bounds of the first window to {x1 + width / 2, y1, x2, y2}
end tell

-- positioning iTerm
tell application "iTerm"
set the bounds of the first window to {x1, y1, x1 + 1000, y1 + 600}
end tell

There are few useful blogposts about the topic. or

or you can use Divvy, which is an amazing window management app.

Generating QR Codes with Google

The google chart API has this feature."+[YOUR_TEXT]+"&chs=[XSIZE]x[YSIZE]"

For instance"Hello World"&chs=120x120"

will generate this

Thursday, June 30, 2011

Changing the default google domain in Chrome

On a mac, make sure that you closed the Chrome browser.

Go to

cd ~/Library/Application\ Support/Google/Chrome

and edit the 'Local State' file,
change the following lines to whatever google domain you want.

"last_known_google_url": "",
"last_prompted_google_url": "",

start the browser.

If you use profiles you have to go to that profile folder and change the 'Local State' file there
cd ~/Library/Application\ Support/Google/Chrome/[PROFILE NAME]

Application Cache whitelisting the master entry

An application cache is a set of cached resources consisting of:

Master entries
These are documents that were added to the cache because a browsing context was navigated to that document and the document indicated that this was its cache, using the manifest attribute.

Explicit entries
These are the resources that were listed in the cache's manifest in an
explicit section (CACHE).

Fallback entries
These are the resources that were listed in the cache's manifest in a fallback section.

The resource that declares the manifest (with the manifest attribute) will always get taken from the cache, whether it is listed in the cache or not, even if it is listed in an online whitelist namespace.
This means that your HTML that includes the manifest file will be always a master entry which is cached and accessed from the cache even the client is online.
Let's face it, this is a pain in the neck in same cases.

There is a simple workaround
1. create an OTHER HTML that will include the manifest file
2. from the ORIGINAL HTML remove the manifest include and create an iframe that includes the OTHER HTML

In this case the master entry will be this OTHER HTML, which does not affect whitelisting the ORIGINAL HTML.

I'd like to emphases that this is just a workaround and i'd like to have a better solution.

You can also follow the related whatwg discussion.

Tuesday, June 28, 2011

Migrating to Dotcloud CLI 0.4.x with 'pip: error: no such option: -u'

Checking the version number
$ dotcloud --version
DotCloud CLI version 0.3.1

Installing Pip (it is a tool for installing and managing Python packages)
$ sudo easy_install pip

Installing the dotcloud CLI 0.4.x
$ sudo pip install --upgrade dotcloud

In the dotcloud migration document they use pip -U but in Pip version 1.0.1 there is no such an option.

Checking the version number again.
$ dotcloud --version
DotCloud CLI version 0.4.0

All right.

Friday, June 24, 2011

Image width/height with Imagemagick in Command line

Imagemagick comes handy when you need information from an image.

# width
w=`identify -format "%w" image.png`

# height
h=`identify -format "%h" image.png`

More information on Imagemagick's identify.

Friday, June 3, 2011

URL shortener algorithm

Here is a simple hashing algorithm that generates a short string for a given ID. This can be used for example in an URL shortener where you store the full URL under an ID and use this algorithm to generate a sort string to reference that ID.

more on that on stackoverflow or on

Monday, May 30, 2011

useful iterm2 shortcuts

iTerm2 is a good replacement for Terminal on OS X

Splitting the window: Command+D to split the window vertically, or Command+Shift+D to split the window horizontally.

Switching between the sub-windows: Command+[ or Command+] or Command+Opt+arrows

Fullscreen: Command+Enter

Saturday, May 21, 2011

req.body undefined in POST request in Express js

You have to use a bodyparser to process the body of a POST request


and put this before the routing definition, like this

app.configure('development', function() {

console.log("Development mode");

app.configure(function() {

here is the related google groups thread.

Sunday, May 15, 2011

bash history

Bash history preserved in ~/.bash_history there are a few ways to search it.
history | grep

history | grep git

the output would be like that
475 git checkout -f
479 gitx
481 git co sp/sprint1
487 git co master
488 git branch -D sp/sprint1
489 git br
491 git co sp/sprint1
496 git diff | gitx
502 git st
510 history | grep git

the followings will reference to line '502 git st'
> !502

# counting back from the last one
> !-1

# same as !-1
> !!

using the last event starting with 'git'
> !git

Or press Ctrl-R, and as you start typing the search goes back in reverse order to the first command that matches the letters you’ve typed.

Once you’ve found the command you have several options:

- Run it verbatim – just press Enter
- Cycle through other commands that match the letters you’ve typed – press Ctrl-R successively
- Quit the search and back to the command line empty-handed – press Ctrl-G

if you're using the history a lot you may want to add these line to your bash init file (~/.bash_profile)

# remove duplicates from the history
export HISTCONTROL=erasedups

# increases the history size
export HISTSIZE=10000

# ensures that when you exit a shell, the history from the session is appended to bash_history
shopt -s histappend

I copy and pasted from the following articles
working-with-history-in-bash, bash-history-reverse-intelligent-search, man history

i like Bash a lot.

top commiters on a git branch

You want to have a list of contributors sorted by number of commits?

git log --format=format:%an | sort | uniq -c | sort -r

will output something like that

1081 Mito
1033 sudo
872 Yusuke
478 morita
423 Yuki
396 Takahiro

Sunday, May 8, 2011

Sniffing Android Tablets

On Android devices the "Mobile" string in the User Agent indicates that the device would prefer a version of the website optimized for Mobile (small form factor devices).
Tablets don't have this, for example

Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; device Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Safari/533.1

unlike phones

Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

This can be used to detect Android tablet devices

is_androidmobile = request.user_agent =~ /android/i && request.user_agent =~ /mobile/i

in context

def is_mobile?
is_iosmobile = request.user_agent =~ /iphone|ipod/i
is_androidmobile = request.user_agent =~ /android/i && request.user_agent =~ /mobile/i

return is_iosmobile || is_androidmobile

more on that here,

Tuesday, April 26, 2011

my ~/.gitconfig file

name = Viktor Kelemen

diff = auto
status = auto
branch = auto
interactive = auto
ui = true
pager = true

[color "status"]
added = yellow
changed = green
untracked = cyan

pager = less -FRSX

co = checkout
st = status
ci = commit
co = checkout
w = whatchanged
lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative

You can find more about .gitconfig customization on Hackernews or on Stackoverflow

Thursday, April 21, 2011

Get HTTP status code with curl in bash

curl --write-out %{http_code} --silent --output /dev/null URL

and then wrapping it into a function

getHTTPCode () {
echo $(curl --write-out %{http_code} --silent --output /dev/null $1)

response=$(getHTTPCode URL)
echo $response

Monday, April 18, 2011

Failed to install db46 on Snow Leopard

I have a brand new macbook (2011/04/19) and have some trouble with installing db46 with ports

port install db46

fails badly and complains about dependencies.

The easiest fix is to install it without java (and you don't need java)

sudo port -v selfupdate
port clean db46
port install db46 +no_java

There are other articles about this problem, How to fix db46 problem macport installation
or MacPorts 1.8.2 fails to build db46 on Mac OS X 1.6.3

Friday, April 15, 2011

Joyent Smartmachine Nodejs log

tail -f /var/svc/log/site-node-service\:default.log

Thursday, April 14, 2011

Reset Joyent Smartmachine Nodejs git repo

cd ~
rm -rf repo
mkdir repo
cd repo
git --bare init
cp /opt/nodejs/post-receive* hooks/
cd ~

Deleting the old repo, creating a new one and then copy the post-recieve hooks.

Saturday, March 26, 2011

Turning off case-sensitive tab completion in bash

/etc/inputrc deals with the mapping of the keyboard for certain situations.


set completion-ignore-case on

to the file turns off case-sensitivity in tab completion.

echo set completion-ignore-case on | sudo tee -a /etc/inputrc

Thursday, March 10, 2011

Saturday, March 5, 2011

Building Xcode Projects From the Command Line

xcodebuild -project myProject.xcodeproj -alltargets

md5sum on Snow Leopard

The MD5 hash (or checksum) functions as a compact digital fingerprint of a file.

You can check the md5 hash of a file with the md5 command
md5 test.txt

The output looks like this
MD5 (test.txt) = ab41fdba223f971be13b1845122353cb

Tuesday, March 1, 2011

Dropbox as a git repo

In your Dropbox folder
mkdir Repositories
cd Repositories
mkdir myNewProject.git
cd myNewProject.git
git init --bare

In your project
cd ~/workspace/MyNewProject
git remote add origin ~/Dropbox/Repositories/myNewProject.git
git push origin master

more on this topic, using-gitdropbox-together-effectively or How to use Dropbox as a git repository

Monday, February 28, 2011

Supervisor for NodeJS

Supervisor runs your nodejs programs and restarts them when a *.js file changes

npm install supervisor

supervisor -p server.js -w .
This example runs server.js and watches the current folder, if a js file changes in this folder it restarts the server.js

Installing NodeJS from source on Snow Leopard

git clone
cd node

mkdir ~/local
./configure --prefix=$HOME/local/node
make install
export PATH=$HOME/local/node/bin:$PATH

Now if you open a new terminal window

node --version

you should see the new version number.

Get page response time with bash

(time curl URL --head) 2>&1 | grep real | cut -c 6-

for instance

(time curl --head) 2>&1 | grep real | cut -c 6-

the response is something like this

Sunday, February 13, 2011

CoffeeScript Syntax Checker Textmate Bundle

Here is a rudimentary version of my CoffeeScript bundle that performs a quick syntax check.
You can bind this command to CMD + S, so it runs after save.

CoffeeScript-Syntax-Checker-Textmate-Bundle on Github

Building CoffeeScript from source

CoffeeScript includes a simple build system similar to Make and Rake. Naturally, it's called Cake, and is used for the build and test tasks for the CoffeeScript language itself.

git clone
cd coffee-script

To build the whole system
bin/cake build:full

To build the script for inclusion in the browser
bin/cake build:browser
MINIFY=false bin/cake build:browser

you may need to install uglify-js as well
npm install uglify-js

Friday, February 11, 2011

Infinite webkit keyframe animation

Here is a simple example of an infinite animation.

@-webkit-keyframes infinite-spinning {
from {
-webkit-transform: rotate(0deg);
to {
-webkit-transform: rotate(360deg);

#box {
-webkit-animation-name: infinite-spinning;
-webkit-animation-duration: 1s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
width: 100px;
height: 100px;
background: #00f;
<div id="box">

Thursday, February 10, 2011

Janus vs 'unable to determine script type'

Update 2011/02/14
Janus developers pulled my changes so if you checkout the latest code you won't see this problem.

Janus is a basic distribution of vim plugins and tools intended to be run on top of the latest MacVIM snapshot.

I tried to install it today but i got this 'unable to determine script type' error

I opened the Rakefile and figured out that the problem is that the does not response.

I looked for mirrors and found one on github, git://
I replaced all the lines with, it seems working now.

Here is the diff for the Rakefile

Wednesday, February 9, 2011

Get folder size on OSX

Haruka had this problem, here is a simple solution

du (abbreviated from disk usage) is a standard Unix program used to estimate the file space usage—space used under a particular directory or files on a file system.

Tuesday, February 8, 2011

You want to attend GoogleIO 2011?

I'm sorry, but you cant!
It was sold out in the first hour after the registration

Good luck in 2012 ;)

The good news is that the GoogleIO 2011 will be live-streamed and the videos will be available from the WebSite later.
Stay tuned!

Monday, February 7, 2011

Customized google maps

You change the look and feel of google maps easily.

Here is a simple example that turns off all labels on the map

map = new google.maps.Map(mapContainer, {}));

var noLabelStyle = new google.maps.StyledMapType([ {
featureType: "all",
elementType: "labels",
stylers: [
{ visibility: "off" }
}], {
name: "no_labels_style"

map.mapTypes.set('stylename', noLabelStyle);

The most important part is the google.maps.StyledMapType class.
Its constructor expects an array, and that describes which element should be visible and how.

You can find the details documentation in the API reference.

Editing files in the user's path

I have lots of scripts in my path but the actual location differs.

If i have to edit them i often do
vim `which FILE_NAME`

for example
vim `which port_utility`

The which utility takes a command name and searches the path for each executable file that would be run had this commands actually been invoke.

Apache on Snow Leopard, "ulimit: open files: cannot modify limit: Invalid argument"

When I started apache on my Snow Leopard i got a weird exception

/usr/sbin/apachectl: line 82: ulimit: open files: cannot modify limit: Invalid argument

So I opened the script and found that there is something wrong with $ULIMIT_MAX_FILES

The error message says that 'cannot modify limit' so i changed its value to empty string

# ULIMIT_MAX_FILES="ulimit -S -n `ulimit -H -n`"

Voila, it works, but deeper investigation need.

Base64 encoding

Base64 is a group of similar encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.
Base64 encoding schemes are commonly used when there is a need to encode binary data that needs be stored and transferred over media that are designed to deal with textual data.

to encode

openssl base64 -in INPUT_FILE -out OUTPUT_FILE

and to decode from Base64:

openssl base64 -d -in INPUT_FILE -out OUTPUT_FILE

Sunday, February 6, 2011

Email filtering with Sieve

Sieve is a programming language that can be used to create filters for email.

I use Sieve to manage my emails on the company's IMAP server.

require "fileinto";

if address :is "From" "" {
fileinto "Support";

elsif header :contains "Subject" ["Develop", "Codereview"] {
fileinto "Develop"

else {
redirect "";

Saturday, February 5, 2011

Finder shortcuts

Today I realized that i don't know enough Finder shortcuts, here you are.

Command-A Select All Items
Command-C Copy Selected Items
Command-D Duplicate Selected Items
Command-F Search with Spotlight
Command-H Hide Window
Command-I Open Get Info (Property) Pane

Command-M Minimize Window
Command-N Open New Window
Command-O Open Selected Items
Command-V Paste Items
Command-W Close Finder Window

Command-1 View as Icons
Command-2 View as Lists
Command-3 View as Columns
Command-4 View as Coverflow

Command-Shift-A Go to Application Folder
Command-Shift-H Go to Home Folder
Command-Shift-N Create New Folder
Command-Option-O Open File and Close Finder

Friday, February 4, 2011

Creating a NPM package

NPM is a package manager for node.

Creating packages with NPM is not difficult so here are the steps.

1. Creating the package.json

Here is an example
"name": "packagename",
"version": "0.0.1",
"description": "Package description",
"main": "package.js",
"keywords": [
"repository" : {
"type" : "git",
"url" : ""

2. Linking it with NPM

npm link

3. Publishing the package

First, you have to create a user in the repo.
npm adduser

Then you can publishing the package
npm publish

This is a good resource (Introduction to npm) but for some strange reason it was difficult to read, maybe the writing style.

Wednesday, February 2, 2011

Reload the browser when files change on OSX

Web front-end development often looks like this, you change the code, which can be HTML, CSS, JavaScript, Ruby whatever and then you head over to the browser and reload it to see the changes.

This is not a big deal, but what if the browser could automatically does the reload.

My solution has three parts.
  1. You can detect file change with Kicker.

  2. Set the focus to the browser and reload it with AppleScript.

  3. Set the focus back to your texteditor.

Let's combine these

kicker -e "osascript reload-browser.applescript;focus-textmate.applescript" FOLDER_TO_WATCH

In my case this looks like this

kicker -e "osascript ~/workspace/MacGyver/reload-browser.applescript;osascript ~/workspace/MacGyver/focus-textmate.applescript" src/

You can find the reload_browser.applescript here and the focus-textmate.applescript here.

Friday, January 28, 2011

Changing the default style in Kod

Kod is a promising text editor for OS X.

One of the great things is that, you can style the editor with CSS.

mkdir ~/.kod
cp /Applications/ ~/.kod/

defaults write se.hunch.kod style/url ~/.kod/default.css

kod ~/.kod/default.css

then don't forget to reload the style in Kod, View menu/Reload style

Thursday, January 27, 2011

Simulating mouse click on Snow Leopard

After googling for 1 hour i came up with the following python script.

import sys
import time
from Quartz import *

def createMouseEvent(type, posx, posy):
theEvent = CGEventCreateMouseEvent(None, type, (posx,posy), kCGMouseButtonLeft)
CGEventPost(kCGHIDEventTap, theEvent)

if __name__ == '__main__':
x = int(sys.argv[1])
y = int(sys.argv[2])

createMouseEvent(kCGEventLeftMouseDown, x, y);
createMouseEvent(kCGEventLeftMouseUp, x, y);

Usage: python 100 100
It'll move the mouse to (100, 100)

Here is the same script on github.

I used the following sources
metapep's blogpost
pepijndevos's PyMouse
GeekOrgy's Python script
a stackoverflow entry


Tuesday, January 25, 2011

Telling time in different timezones with bash on OSX

You can use the TZ variable to affect the execution of date command.

Current time in Japan Standard Time (JST)
TZ=Asia/Tokyo date

Pacific Standard Time (PST)
TZ=America/Los_Angeles date

Eastern Standard Time (EST)
TZ=America/New_York date

Central Standard Time (CST)
TZ=America/Chicago date

Coordinated Universal Time (UTC) / Greenwich Mean Time (GMT)
TZ=Europe/London date

Central European Time (CET)
TZ=Europe/Budapest date

Here is how i use it.

Escaping special HTML characters in JSP

If you have a string that contains special characters such as '&' and you want to display this in a JSP page, you may get a ' The content of elements must consist of well-formed character data or markup.'

This code will fail if linkParm contains a '&'
<a href="${userBean.linkParm}">
main link

The short answer is
<a href="<c:out value='${userBean.linkParm}'/>">
main link

This seems overkill, indeed.

Thursday, January 20, 2011

EJS default escaping

In EJS (Embedded JavaScript) escaping is a default behaviour.

// escape by default

This can easily mess up a couple of things (including JSON, HTML rendering), luckily you can turn it off by using

// render out string

Monday, January 17, 2011

Thursday, January 6, 2011

Iterating through an array in bash

locations=( Roppongi Shibuya Ebisu )

for name in ${locations[@]}
echo $name

Generating random locations around a location


def generateLocation(startlat, startlon, maxdist):

# converting them radians
startlat *= pi / 180
startlon *= pi / 180
rand1 = random.random()
rand2 = random.random()

maxdist = maxdist / earthradius
dist = acos(rand1*(cos(maxdist) - 1) + 1)
brg = 2*pi*rand2

lat = asin(sin(startlat)*cos(dist) + cos(startlat)*sin(dist)*cos(brg))
lon = startlon + atan2(sin(brg)*sin(dist)*cos(startlat), cos(dist)-sin(startlat)*sin(lat))

if lon < -pi:
lon = lon + 2 * pi

if lon > pi:
lon = lon - 2 * pi

lat *= 180 / pi
lon *= 180 / pi

return [lat, lon]

Tuesday, January 4, 2011

Turn off SpringSource Tool Suite Dashboard

SpringSource Tool Suite 2.3.2 boots really slowly and it can be even slower if it opens the Dashboard at startup.
Lucky you can turn it off, not trivial though.

Dashboard has 4 tabs on the bottom (Dashboard, Knowledge Base, Extensions and Configuration).
At the Configuration tab there is a checkbox, Show On Startup.