Tuesday, December 27, 2011

Autoselection of checkboxes in a table

The code doing selection
$(function () {
    "use strict";
    var toggleSelect = $("#all"),
        checkboxes = $("#table").find("tbody input[type=checkbox]");
    toggleSelect.click(function () {
        checkboxes.attr('checked', $(this).is(":checked"));
    });
    checkboxes.click(function () {
        toggleSelect.attr('checked', checkboxes.length === checkboxes.filter(':checked').length);
    });
});
A sample table
Username Phone Number
User 1 0123456789
User 2 0133456789

Tuesday, December 6, 2011

Activate VE from Django's manage.py

To transparently activate virtual environment from project's manage.py insert the code below right after #!/usr/bin/env python
activate_this = '/ABSOLUTE/PATH/TO/ENVIRONMENT/FILES/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

Thursday, October 20, 2011

Madly follow PEP8 with git help

If you intended or are obliged to strictly comply to PEP8 it may be useful to have a git hook that takes care of checking your code before you have committed and prevents you from amending previous commit again and again.

So, in .git/hooks/ directory of your repository create a file with name pre-commit and put

#!/bin/sh

# comma-separated list of files and directories which are not for checking
SKIP=migrations,bootstrap.py,dodo.py,manage.py

pep8 -r --exclude=$SKIP .

UPDATE: The code above checks all the project Python files. To limit checking only for files going to be committed

#!/bin/sh

FILES=$(git diff --cached --name-status | awk '$1 $2 { print $2}' | grep -e \.py$)
if [ -n "$FILES" ]; then
    pep8 -r $FILES
fi

The command shows all staged files, next only the filenames are left and filters Python files. If any they are to be checked with PEP8 utility.

Saturday, October 15, 2011

Word and text translation bookmarklet

Sometimes (I hope rarer and rarer :)) I need to translate an unknown foreign word on the page. I used to select it, open Google Dictionary Translate, paste it, set source and destination languages if needs and only then press the button to translate it.

Some time later I discovered bookmarklets. I liked the approach and made one for myself.

Drag this link En<>Ru the bookmark panel to be able translate words or text.

To change default source and destination languages put their codes in place of en and ru.

Source code.
(function() {
    var t;
    try {
        t= ((window.getSelection && window.getSelection()) ||
            (document.getSelection && document.getSelection()) ||
            (document.selection &&
            document.selection.createRange &&
            document.selection.createRange().text));
    }
    catch(e){
        t = "";
    }

    if(t && (t=t.toString()) && t.length){
window.open("http://translate.google.com/?sl=en&tl=ru&hl=en&text="+t+"#en|ru|"+t);
    }
})()

I used Javascript Compressor to get compressed version to use it in the bookmarklet.

Friday, October 14, 2011

Uninstall XCode

To uninstall XCode from Mac OS X run in terminal:
sudo /Developer/Library/uninstall-devtools –mode=all

Tuesday, October 11, 2011

Upgrading Mac OS X to Lion and dealing with virtualenv

I happened to have successfully upgraded my Snow Leopard to Lion. It looks nicer, softer and so forth. But I depend on my MacBook Pro in my work and have to have everything working.

Actually after upgrade everything were broken: python did not work properly, system paths were set in their defaults. So it was absolute mess.

First, as I learned it from Snow Leopard, I have downloaded new XCode from Mac App Store. It quote big and it took all night (while I was sleeping) for downloading. In the morning I installed and all became better but one. Virtual environments were still spoiled and did not work.

After a few tries and researches I came up with the following:

sudo easy_install pip # it installs new (or even) pip version
sudo pip install virtualenvwrapper

After those commands all get working.

Thursday, October 6, 2011

CKEditor autosave plugin

If you need autosave function for the CKEditor I made a plugin. It allows to save automatically the work as you've stopped typing.

UPD  Oct 6, 2011: Plugin has moved to GitHub.

Monday, August 15, 2011

Avoid command repeating in Bash

If you are already done with mess of the same commands in bash history, just put that in your ~/.bashrc
export HISTCONTROL=ignoredups:erasedups
ignoredups prevents the history from duplicates
erasedups if a command is already in the list it will be removed at the old position and put in the beginning of the history list

Wednesday, August 3, 2011

Clients of the webservice

Some time ago my iPhone happened to get lost. There were many clients of well known services installed and all of them had been logged in and most part of them had their passwords saved. To prevent access from my lost phone I had to change password for almost all services I used.

Clients should avoid using re-authentication with login and password. It implies saving them on the client side. Conversely, the application should either ask for OAuth authentication or for login and password only once. Latter requires the server to provide the key to login next time with.

Those techniques allow the web server to control all the clients without changing the password if something has happened to one of the clients.

Thursday, June 30, 2011

Yesterday date

$yesterday = date('Y-m-d', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y")))

UPD: (thanks to stamm)
$yesterday = date('Y-m-d', strtotime('- 1 day')); 

Tuesday, June 28, 2011

Kwargs in Python

Recently I noticed that function cannot accept unicode strings as parameter names given in kwargs. They must be converted to strings.

I made a sample script
import sys

print "Version: %d.%d.%d\n" % sys.version_info[:3]

string_params = {'a':1, 'b': 2}
unicode_params = {u'a':1, u'b': 2}

def f(a,b):
 print "params: ", a, b

print "Run with string params:"
f(**string_params)

print "\nRun with unicode params:"
f(**unicode_params)

As output I got
Version: 2.5.1

Run with string params:
params:  1 2

Run with unicode params:
Traceback (most recent call last):
  Line 15, in 
    f(**unicode_params)
TypeError: f() keywords must be strings

To check out it online.

Disable Firefox cache for developing

To disable caches while you're developing and testing in Firefox:
  1. Type about:config in FF address bar;
  2. Set to false the following params:
    • network.http.use-cache
    • browser.cache.offline.enable
    • browser.cache.disk.enable
    • browser.cache.disk_cache_ssl
    • browser.cache.memory.enable
Beware, it totally disables cache in FF!

Monday, June 27, 2011

Make string html-safe

To make a string HTML-safe (convert & to &amp;, > to &gt; and so forth):

>>> import cgi
>>>
>>> test_string = "This is <unsafe> string & it contains wrong symbols"
>>>
>>> print cgi.escape(test_string)
This is &lt;unsafe&gt; string &amp; it contains wrong symbols

Wednesday, June 22, 2011

Run Django via WSGI without web server

Recently I faced a problem - I needed to test updated Django WSGI-runner script. But I didn't have a web server on my computer. And I didn't want to install it. So, how to deal with that?

I found out about Werkzeug. It was supposed to solve my issue. To install it run system-wide
sudo pip install werkzeug
I made a runner script run.py that makes a dev server with Werkzeug and voila:

run.py
from werkzeug.serving import run_simple
from wsgi import application

run_simple('127.0.0.1', 4000, application)

where wsgi.py is former django.wsgi file.

Thursday, May 26, 2011

Adding a new user

To create a new Postgres user.
First, create a new Linux user:
sudo useradd -M -N username # (do not create hoMe dir; do not add to group "userName")
sudo passwd username # enter password 'username'

And add user with the same name to Postgres:
psql -h 127.0.0.1 -p 5432 -U username -W -d template1 # insert your hostname and port if different 
In psql:
CREATE USER username WITH PASSWORD 'username';
ALTER USER username CREATEDB; -- allow user to create databases 

Monday, April 11, 2011

How to satisfy dependencies for your python projects

You need a text file in your project with your dependencies, i.e. REQUIREMENTS, with a list of packages your project depends on.

PIP's requirement file format (detailed):
<package-name>[==<version>]
-e <repository address>#egg=<desirable-package-name>

And when you need to init the project in a new place you'd like to run:
# init or activate a virtual environment
(virtual-env)$ pip install -r REQUIREMENTS

That's all. You packages will be automatically installed. And you can run that command whenever you want (i.e. a new dependency has been added) - it just recheck all mentioned packages and install new ones.

Thursday, April 7, 2011

Python's virtual environment

You probably would like to use separate sets of packages for your projects and whilst not to spoil your system's environment. This problem can be solved by using virtual environments.

Make initial setup:


To configure virtualenvwrapper:

  1. Create a directory for the virtual environments:
    mkdir ~/projects/.envs
  2. Add to ~/.bashrc:
    export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python
    export WORKON_HOME=~/projects/.envs
    export PROJECT_HOME=~/projects
    
    source /usr/local/bin/virtualenvwrapper.sh
  3. Run:
    source ~/.bashrc

Initial setup has been done. Now let's create a new virtual enviroment for Test project in ~/projects/test
mkvirtualenv test
workon test
Now you're in the 'test' environment. To install new packages you can use, for instance, pip.

Friday, April 1, 2011

Big brother is watching you

Do you doubt whether Google knows about your Wi-Fi router location? Try this on your *nix-machine:

iwlist wlan0 scan | sed -n 's/.* Address: //p;T;s/ //g;q' | sed 's/.*/{version:1.1.0,host:maps.google.com,request_address:true,address_language:'${LANG/.*/}',wifi_towers:[{mac_address:"&",signal_strength:8,age:0}]}/' | curl -sX POST -d @- www.google.com/loc/json | sed -e 'h;s/.*latitude":\([^,]*\).*/\1/;G;s/\n[^\n]*longitude":\([^,]*\).*/,\1\n/;s|^|http://maps.google.com/maps?q=|;x;s/[,{]/\n/g;s/["}]//g;s/:/\t/g;s/\n//;G'

Nice, isn't it?

Wednesday, March 30, 2011

Friday, March 25, 2011

Vim necessary commands

Reload the file with selected encoding:
:e ++enc=<encoding>

Friday, February 25, 2011

Force FF not to fill up input by its 'memorized' state after refresh

If it is a very annoying thing for you, use autocomplete="off" for every input you want to avoid memorizing.

Wednesday, February 16, 2011

Patching with git diff

To create patch file:

git diff --no-prefix > filename

To apply it:

patch -p0 < filename

If you have a patch file that's been created without --no-prefix, apply it

patch -p1 < filename

Tuesday, February 15, 2011

Launch Virualbox image from command line

To launch a VirtualBox image directly without GUI interface do the following

vboxmanage startvm name

where name is exactly name is shown in VirtualBox GUI.

Git Delete Last Commit

Once in a while late at night when I ran out of coffee, I commit stuff that I shouldn't have. Then I spend the next 10 - 15 minutes googling how to remove the last commit I made. So after third time I wanted to make a record of it so I can refer to it later.

If you have committed junk but not pushed,

git reset --hard HEAD~1

HEAD~1 is a shorthand for the commit before head. Alternatively you can refer to the SHA-1 of the hash you want to reset to. Note that when using --hard any changes to tracked files in the working tree since the commit before head are lost.

If you don't want to wipe out the work you have done, you can use --soft option that will delete the commit but it will leave all your changed files "Changes to be committed", as git status would put it.

Now if you already pushed and someone pulled which is usually my case, you can't use git reset. You can however do a git revert,

git revert HEAD

This will create a new commit that reverses everything introduced by the accidental commit.

From here.

Thursday, February 10, 2011

Git support in Netbeans

To make Netbeans work with GIT as simple and comfortable as with Mercurial or SVN use nbgit.

Monday, January 31, 2011

XPath at HTML in Python

This technique allows to treat HTML code as XML (if even HTML is not totally valid) and use XPath expressions over it.
from lxml import etree

content = '... some html ...'
# use the HTML parser explicitly to provide encoding
parser = etree.HTMLParser(encoding='utf-8')
# load the content using the parser
tree = etree.fromstring(content, parser)
# we've got a XML tree from HTML
# now get all links in the doc
links = tree.xpath(".//*/a")
for link in links:
    href = link.get('href') # get tag's attribute
    name = link.text() # text between open and close tags

Some links:
API reference
Usage tutorial

Monday, January 17, 2011

How to add your own favicon to your blogger.com blog

To get your own favicon to your blog:

  1. Store a picture you want to be the favicon in PNG and ICO formats in any web-accessible place. I used Google Docs for this because it allows to store any kind of files in public access.
  2. Put in your template this code
    <link href="url/to/favicon.png" rel="icon" type="image/png"></link>
    <link href="url/to/favicon.ico" rel="shortcut icon"></link>
  3. Notice that you must place the code above after
    <b:include data='blog' name='all-head-content'/>
    
    only. Otherwise blogger.com writes its own favicon and you waste your efforts.