Showing posts with label admin. Show all posts
Showing posts with label admin. Show all posts

Sunday, July 12, 2009

xorg options for Jaunty

Since Jaunty the Ubuntu people thought it would be a good idea to cripple the xorg settings (they disabled middle mouse button emulation and ctrl+alt+backspace xorg reset hotkey).

Luckily this can be fixed by editing the /etc/X11/xorg.conf file by adding the following:
# Enable middle mouse button emulation (left+right click at the same time):
Section "InputDevice"
Identifier "Configured Mouse"
Driver "mouse"
Option "CorePointer"
Option "Device" "/dev/input/mice"
Option "Protocol" "ExplorerPS/2"
Option "ZAxisMapping" "4 5"
Option "Emulate3Buttons" "true"
EndSection

# Enable crl+alt+backspace xorg reset
Section "ServerFlags"
Option "DontZap" "false"
EndSection

Friday, July 10, 2009

Ubuntu Jaunty (9.04) Python Tix fix

The "tix" (Tk Interface eXtension) version that Ubuntu Jaunty ships is broken for python (2.x and 3.x; stock and custom). If you run the tix demo applications, most of them will fail with something like: _tkinter.TclError: unknown color name "{#c3c3c3}"

The solution I came up for now was to compile and install tix manually, which solved the problem. Here is how it goes.

  1. Download the newest tix sources from here and extract them % tar -xvzf Tix8.4.3-src.tar.gz; cd Tix8.4.3
  2. Install tcl and tk 8.4 packages % sudo aptitude install tclx8.4 tclx8.4-dev tk8.4 tk8.4-dev (Note: Ubuntu ships with newer version - 8.5 which tix does not understand).
  3. Configure the tix sources % ./configure --with-tclconfig=/usr/share/tcltk/tcl8.4 --with-tkconfig=/usr/share/tcltk/tk8.4 (Note: if you do not specify the options than the config script will complain and die. Set the prefix option if you don't want it installed at /usr/lib/Tix8.4. Check ./configure --help if unsure)
  4. Compile the sources: % make
  5. Test the compiled sources: % make test (at the end there should be a number of Passed tests and 0 Failed - if something failed then you have to search for the problem).
  6. Install the thing: % sudo make install
Now the tix examples should work fine. Alternatively you can also use this handy shell script:
#! /bin/bash
wget -c http://downloads.sourceforge.net/sourceforge/tix/Tix8.4.3-src.tar.gz
tar -xvzf Tix8.4.3-src.tar.gz
cd Tix8.4.3
sudo aptitude install tclx8.4 tclx8.4-dev tk8.4 tk8.4-dev
./configure --with-tclconfig=/usr/share/tcltk/tcl8.4 --with-tkconfig=/usr/share/tcltk/tk8.4
make
make test && sudo make install || echo "Test failed, check output.."

Note: the default installation target is /usr/lib/Tix8.4.3/, so removing the thing consists of % sudo rm -rvf /usr/lib/Tix8.4.3

Note:
The Launchpad bug report for the bug can be found here.

My vimrc file

Got to save my .vimrc (vim configuration file) once in a while and now is a good time as I just cleaned it up a bit. Did not tweak it too much, but it has a few handy shortcuts, some for python some just general purpose. The file can be found as gist (revisioned pastebin) here.

And here is a raw paste:
" set tabstop settings
set ts=8
set sw=8

" wrap long lines
set textwidth=80
set linebreak
set smartindent

syntax on
set nocompatible
set novisualbell

" check for external modification
set autoread

" incremental search
set incsearch

" set spelling highlight options
highlight clear SpellBad
highlight SpellBad term=standout ctermfg=1 term=underline cterm=underline
highlight clear SpellCap
highlight SpellCap term=underline cterm=underline
highlight clear SpellRare
highlight SpellRare term=underline cterm=underline
highlight clear SpellLocal
highlight SpellLocal term=underline cterm=underline

" ---------- START OF SHORTCUTS DEFINITIONS (KEY BINDINGS) ----------
"
" INDEX
"
" ,s enable spellcheck highlight
" ,S dissable spellcheck highlight
" ,c-d save all and exit
" ,c trim spaces at end of lines
" ,C trim spaces at the beginning of lines
" ,d insert date in YY-MM-DD format
" ,u insert unix timestamp
" <F2><F3><F4> execute file with python interpreter 2/3 and with argument
" <F5><F6> enable/dissable paste mode
" <F9><F10> exchange spaces with tabs and tabs with spaces
" <F12> general search and replace template

" spell checking shortcuts (ctrl+[sS] to switch it on/off)
map ,s :set spell<CR> :setlocal spell spelllang=en_us<CR> :set spellfile=~/.vim/spellfile.{encoding}.add<CR>
map ,S :set nospell<CR>

" add python 2, 3 and 3 with arguments execution to F2-F4
au filetype python nmap <F2> <esc>:w<CR>:tabfirst<CR>:! python %<CR>
au filetype python nmap <F3> <esc>:w<CR>:tabfirst<CR>:! python3 %<CR>
au filetype python nmap <F4> <esc>:w<CR>:! python3 %

" add save all and exit shortcut to ctrl+d
nmap <c-d> <esc>:xa<CR>

" add shortcut for switching paste mode on/off (F5-F6)
nmap <F5> :set paste<CR>i
nmap <F6> :set nopaste<CR>

" shortuct for swapping spaces with tabs (F9-F10)
nmap <F9> :%s/ /\t/g<CR>
nmap <F10> :%s/\t/ /g<CR>

" general search and replace template
nmap <F12> :%s///g

" suppress all spaces at end/beginning of lines
nmap ,c :%s/\s\+$//<CR>
nmap ,C :%s/^\s\+//<CR>

" insert current date in YY-MM-DD or UNIX time format
map ,d :r!date +\%Y-\%m-\%d<CR>hJi
map ,u :r!date +\%s<CR>

""" --------- END OF KEYBINDINGS --------------

" set execution bit for scripts
au bufwritepost *.sh silent !chmod +x %
au bufwritepost *.x.py silent !chmod +x %

" if we edit makefiles, make sure that tabs are not replaced with spaces
au filetype make setlocal noexpandtab

" set plaintext documents to a text with of 72 chars
autocmd BufRead *.txt set tw=72

Saturday, July 4, 2009

Terminal command shortcut scirpt

You know those terminal commands that you execute all the time but are too lazy to put in a shell alias or those special commands you need a lot of time to figure out and then mostly forget about it and then the next time you need it you cruse yourself you did not save it somewhere? This script aims to address this problems.

It stores commands terminated with newline in a data file (~/.scdata). When you invoke it with the number argument, it executes that line number (beginning with 0). Without argument it list the available commands with id's and prompts for id to execute.

Now, when you figured out some complicated command with a lot of options, like 'rsync -av /myhome /backup_drive' you can simply echo it to the data file (echo 'rsync -av /myhome /backup_drive' >> ~/.scdata) and recall it anytime with the prompt utility.

Your ~/.scdata with 4 commands (0-3) could look like this:

echo hello
cp foo bar
rsync -av /myhome /backup_drive
echo 'and so forth'

Now running the script with argument '2' ($ sc.py 2) for instance would run the rsync command.

Syntax highlighted version here.

#! /usr/bin/env python3

"""
Terminal command shortcut scirpt.

This script reads a command data file (~/.scdata) and executes commands from it.

There are two command execution models:
1. by argement, if you invoke it with a number, it executes this command
and exits. If you invoke it with -e opion, it opens the command file
for editing and then enters the main loop.
2. by loop, if you invoke it withouth an argument, it prints the
availible commands and promts for command number (id) to execute.

There are also 2 special non-numeric loop commands:
e: edit command file and return to main loop
q: quit program
"""

import os, sys, time

def get_editor():
try:
editor = os.environ['EDITOR']
except:
editor = 'vim'
return editor

def read_data(editor, data_file):
try:
with open(data_file, 'r') as f:
data = f.readlines()
data = [item.strip() for item in data]
data = dict(enumerate(data))
return data
except:
print('Data file not found, first start?.. Creating data file')
print('Please add some command to it..')
time.sleep(3)
with open(data_file, 'w') as f:
pass
os.system(editor + ' ' + data_file)
return read_data()

if __name__ == '__main__':

editor = get_editor()
data_file = os.path.join(os.path.expanduser('~'), '.scdata')

data = read_data(editor, data_file)

if len(sys.argv) > 1:
if sys.argv[1] == '-e':
print('Opening data file for editing..')
time.sleep(1)
os.system(editor + ' ' + data_file)
try:
cmd_task = int(sys.argv[1])
os.system('clear')
print('executing ', data[cmd_task], '\n')
os.system(data[cmd_task])
print('\nexecution done, exiting..')
sys.exit()
except (IndexError, ValueError):
pass

while True:
os.system('clear')
print('Shell command shortcut utility\n' +
'==============================\n\n' +
'Currently availible commands are:\n')
for cmd_task, cmd in data.items():
print(cmd_task, '\t', cmd)
print('\nPlease enter a command (e, q, or number)\n')
try:
cmd_task = input('% ')
if cmd_task == 'e':
os.system(editor + ' ' + data_file)
data = read_data(editor, data_file)
continue
elif cmd_task == 'q':
print('Quit.. bye!')
sys.exit()
else:
cmd_task = int(cmd_task)
assert(cmd_task <= len(data))
except (AssertionError, ValueError, KeyError):
print('Please enter a valid input ' +
'(h, e, q or number)')
time.sleep(1)
else:
os.system('clear')
print('executing \'{1}\' ..\n'.format(data[cmd_task]))
time.sleep(1)
os.system(data[cmd_task])
print('\nexecution done, hit a key to return..')
input()

Thursday, July 2, 2009

Manual compilation and installation of Python 3.1 on Ubuntu Jaunty

I was taking a look at the feature list of the new Python 3.1 version and noticed the ttk GUI improvements that made me want to test it. Unfortunately I did not found it in the package archives, so I decided to compile it myself. The compiling process took a while as I had to iterate through a few a adoptions, so here is what makes it work properly:

1. You obviously need the source package form wget -c http://python.org/ftp/python/3.1/Python-3.1.tar.bz2 and extract it tar xvjf Python-3.1.tar.bz2 and enter the folder cd Python-3.1

2. You need to install a bunch of packages that are required for some modules, like the tk/ttk one: sudo aptitude install gcc tk8.5-dev libssl-dev libsqlite3-dev libzip-dev libreadline5-dev libbz2-dev libgdbm-dev

3. Now you have to set up the compilation: ./configure --with-computed-gotos . The option comes form the Python homepage news section and adds speed optimisations.

4. Compile the sources: make (this will take some time)

5. Test the compiled sources: make test (this will take even more time)

6. Finally you can install with make install (installation will go to /usr/local/bin) or just test it for instance with ./python Demo/tkinter/ttk/ttkcalendar.py

That's it, enjoy!

Update: Found a Jaunty PPA for Python 3.1 amd64 arch (64bit): https://launchpad.net/~python-dev/+archive/ppa

Tuesday, June 30, 2009

Projgen setup on Ubuntu 9.04 (Jaunty)

Just surfed around some news sites and stumbled upon the moblin (Intel's netbook Linux) site, as the 2.0 release is due. In the dev. section of the site I found projgen, a C/C++/Python project generator based on autotools and GTK. It actually has a nice GUI, though it is still *very* unstable. Now I had some hassle to get it running in the first place, so now I describe what did the trick until it will be fixed:

Note: You'll need git to fetch the sources, if you don't have them, sudo apt-get install git .

First I went to the project site: http://moblin.org/projects/linux-project-generator and did what was written there:

Opened a terminal and fetched the sources: git clone git://git.moblin.org/projgen.git

Installed the stuff that is listed there: sudo apt-get install libmagic-dev libglade2-dev libglib2.0-dev libgconf2-dev libxml2-dev

Entered ./autogen.sh , as it was described, which imediately bitched about missing libtoolize and gtkdocize , which I did not found as packages either. The right packages are: libtool and gtk-doc-tools . Installing these with sudo apt-get install libtool gtk-doc-tools will solve the problem.

Now autogen and
./autogen.sh
make
sudo make install

Now everything is in place, but running projgen will still bitch about a missing libprojgen.so.0, wich is located at /usr/local/lib . To make it work, you have to add it to the ldconfig thing. Do this by adding the path to a etc config file: sudo echo '/usr/local/lib' > /etc/ld.so.conf.d/projgen.conf and then update the cache: sudo /sbin/ldconfig .. Now you can run projgen.

As mentioned, it is still quite not mature right now.

Monday, June 29, 2009

Work session start/end script

There is a set of repetitive tasks I do when I develop something, like check-in, off-site backup, archive integrity checking, etc. To automate this, I wrote a little script that I invoke when I start and stop to work on something for this purpose. The start and end functions should be adapted to personal needs, this one is a bit bare-bone.

Here is what it looks like (syntax highlighted version here):

#! /usr/bin/env python3

"""
Work session start/end script.

This script contains the routines that should be performed before and after a
work session and log it. Currently these are git repository integrity checking
for start up. Change commiting and backup for end of session.

Uses 'rsync' for backup and 'git' for revision control, make sure they are in
place.

The BACKUP_PATH has to be adapted to the syncronization target.

This script is quite safe to use.
"""

import os, sys, subprocess, time, datetime

BACKUP_PATH = '/media/disk'
LOGFILE = 'session.log'

def log(message, logfile=LOGFILE):
timestamp = str(int(time.mktime(datetime.datetime.now().timetuple())))
name = os.path.basename(__file__)
with open(logfile, 'a') as f:
f.write('[' + timestamp + '] ' + name + ': ' + message + '\n')

def start():
status = subprocess.call(['git', 'gc'])
if status != 0:
print ('!! something went wrong with the repository checking!')
print ('(recheck manually with git fsck and restore integrity)')
sys.exit(1)

log('session started')

def end():
os.system('git add .')
os.system('git gui')

if os.path.isdir(BACKUP_PATH):
os.system('rsync -a . ' + BACKUP_PATH)
else:
print('backup path not existent, backup aborted..')

log('session ended')

if __name__ == '__main__':
usage = ('Usage: session.py start|end\n' +
' start: start session\n' +
' end: end session\n')

os.chdir(os.path.abspath(os.path.dirname(__file__)))

if len(sys.argv) == 1 or (
sys.argv[1] != 'start' and sys.argv[1] != 'end'):
print(usage)
sys.exit()

if sys.argv[1] == 'start':
start()
elif sys.argv[1] == 'end':
end()

Sunday, June 28, 2009

.gitignore based clean script

This administrative development script reads the .gitignore file and removes the patters found there from the directory tree. Useful housekeeping script, but also quite powerful, use with care.

Syntax highlighted version here.


#! /usr/bin/env python3

"""
Clean script based on .gitignore file, the 'find' and 'rm' command. It has to
be located in the same directory as the .gitignore file.

This script reads the .gitignore file, parses the patterns found there to a
shell remove command and then executes it.

- With the 'dirs' option it also removes directories.
- With the 'debug' option it just prints the command it would execute and exits.

Uses the 'find' and 'rm' Linux / *NIX / OS X commands, which restricts it to
these platforms.

Note: be careful with this script, it's quite powerful.
"""

import os, sys

def change_to_file_dir():
os.chdir(os.path.abspath(os.path.dirname(__file__)))

def read_clean_patterns():
try:
with open('.gitignore', 'r') as f:
clean_patterns = f.readlines()
except IOError as err:
sys.stderr.write('Could not open .gitignore file: ', err)
sys.exit(2)
return clean_patterns

def create_clean_command(clean_patterns):
clean_patterns = ['-o -name "' + item.replace('\n', '') + '" '
for item in clean_patterns]
first = 0
clean_patterns[first] = clean_patterns[first].replace('-o ', '')
clean_command = str()
for x in clean_patterns:
clean_command += x
if len(sys.argv) > 1 and sys.argv[1] == 'dirs':
clean_command = ('find . \( ' +
clean_command + '\) -exec rm -vrf "{}" \;')
else:
clean_command = ('find . \( ' +
clean_command + '\) -exec rm -vf "{}" \;')
return clean_command

if __name__ == '__main__':
if (len(sys.argv) > 1 and
sys.argv[1] != 'dirs' and
sys.argv[1] != 'debug'):
print('Usage: clean [dirs] [debug]')
print(' dirs: recursive, remove directories too')
print(' debug: only print command, don\'t execute')
sys.exit()

change_to_file_dir()
clean_patterns = read_clean_patterns()
clean_command = create_clean_command(clean_patterns)
if sys.argv[-1] == 'debug':
print ('Clean command is:', clean_command, sep='\n')
else:
os.system(clean_command)