03 January 2013

Linux drivers for USB wireless adapter DWA-140, hardware rev. B3 on raspberry pi

I finally got my Raspberry Pi, a $35 computer with 512MB ram: http://www.raspberrypi.org
After installing raspbian on it (http://www.raspberrypi.org/downloads), I had to prepare drivers for my USB wireless adapter, D-Link DWA-140 with hardware revision B3.

These are the steps I made

  • Install the raspbian on the SD card, boot Linux, and connect to the Internet using Ethernet
sudo apt-get update && sudo apt-get upgrade -y
Wait a very long time until this finishes, and then reboot:
sudo reboot
After reboot
 sudo apt-get install build-essential linux-headers -y
 Then go to the RaLink website (link found at http://wikidevi.com/wiki/D-Link_DWA-140_rev_B3 and https://help.ubuntu.com/community/WifiDocs/Device/Tenda_W311M)
http://www.ralinktech.com/en/04_support/support.php?sn=501
I had to download the 4th link:
http://www.ralinktech.com/en/04_support/license.php?sn=5032

Please input your name and your email address, and save the archive. Next, unpack it:
tar xf DPO_RT5572*
cd DPO_RT5572* 
Change config to support WPA and WPA2
gedit os/linux/config.mk
HAS_WPA_SUPPLICANT=y (was "n")
HAS_NATIVE_WPA_SUPPLICANT_SUPPORT=y (was "n")
To build the driver, I had to make a link to the kernel headers:
sudo ln -s /usr/src/linux-headers-3.2.0-3-rpi /lib/modules/3.2.27+/build
Now, build:
 make
This will take some time, and finally give an error about not being able to copy to /tftpboot, which you can ignore. Next, install:
make install
And this should be all.

12 August 2010

Stop hard disk heavy processes from slowing down the entire machine on Ubuntu

So this is the deal:
We have a machine with many users and some of them are occasionally running hdd-intensive applications. This is an expected activity of the users, BUT it practically prevents other users from doing anything with the machine until the processes with the intensive hdd activities terminate.

This is why I added a "daemon" that runs in the background and checks for any hdd-intensive processes.
If any processes of this type are found, using "ionice", their I/O priority is reduced to "C 3" (idle):
from "man ionice"
"""
Idle. A program running with idle io priority will only get disk time when no other program has asked for disk io for a defined grace period. The impact of idle io processes on normal system activity should be zero. This scheduling class does not take a priority argument.
"""

The tools used here should be already there in Ubuntu. If they are not (or you just want to make sure that they are installed) you can run:
sudo apt-get install iotop util-linux grep mawk findutils

An entire "daemon" consists of adding the following line to "/etc/rc.local", just before "exit 0"

iotop -b -o -d 15 | grep "%" | grep "M/s" | awk '{print $1}' | xargs ionice -c 3 -p
Or you could run almost the same line as an ordinary user and "sudo":
iotop -b -o -d 15 | grep "%" | grep "M/s" | awk '{print $1}' | xargs sudo ionice -c 3 -p
The machine (and its users) are much happier now. :)

Hope this helps somebody else as well.

20 June 2010

Updated Hamachi keep-alive script

Last Updated on June 25, 2010.

I modified the hamachi wrapper script with two functionalities:
  • do NOT restart hamachi if there is nobody to ping
  • DO restart hamachi if there are unreachable hosts
  • DO restart hamachi if its CPU usage goes over 50% - this partly solves the 100% CPU usage problem of hamachi
  • if you modify the script name, the script should keep working - it even works if there is a space in the filename

#!/bin/bash

scriptname="`basename \"$0\"`"

function command_pids {
IFS='
'
RES=""
for p in `ps xo pid,command | grep "$1"`; do
    IFS=' ' hampid=( $p )
    pid=${hampid[0]}
    if [ ".`basename ${hampid[1]}`" == ".hamachi" ]; then RES="${RES} $pid"; fi
done
echo $RES;
}

function hamachi_force_terminate {
    hamachi stop >/dev/null
    sleep 1
    for ham_pid in $( command_pids hamachi ); do
        kill -9 $ham_pid
    done
}

hamachi_running=1
if [ `echo $( command_pids hamachi ) | wc -w` -eq 0 ]; then
    hamachi_running=0;
    #echo "count not detect running hamachi"
else
    hamachi_pcpu=`ps ho pcpu $( command_pids hamachi )`
    if [ `echo $( command_pids hamachi ) | wc -w` -gt 1 ]; then
        echo "multiple running hamachi instances - terminating"
        hamachi_force_terminate
        hamachi_running=0
    else
        if [ `echo "$hamachi_pcpu > 50" | bc` -eq 1 ]; then 
            echo "high CPU usage hamachi instances - terminating"
            hamachi_force_terminate
            hamachi_running=0
        fi
    fi
fi

if [ `ip r | grep default -c` -lt 1 ]; then
    # No internet gateway, exiting!
    exit 1
fi

hamachi_online=`hamachi list | egrep '\* [0-9]' | awk '{print $2}'`
count_unreachable=`hamachi list | egrep 'x [0-9]' | wc -l`

ping_ok=1
for IP in $hamachi_online; do
    ping -c 2 $IP >/dev/null
    if [ $? -ne 0 ]; then
        echo "ping $IP failed!"
        hamachi list | grep $IP
        ping_ok=0;
    fi # if first ping fails then ping is not OK!
    break;
done

if [ $hamachi_running -ne 1 -o $count_unreachable -gt 0 -o $ping_ok -eq 0 ]; then
    echo "restarting hamachi: running $hamachi_running unreachable $count_unreachable ping $ping_ok"
    if [ `pgrep tuncfg | wc -l` -eq 0 ]; then sudo /sbin/tuncfg; fi
    hamachi_force_terminate
    hamachi start
    CNT=1;
    echo -n "Logging in... " ;
    while [ `hamachi login | grep -c failed` -eq 1 -a $CNT -lt 100 ]; do 
        echo -n "$CNT "; 
        let CNT=$CNT+1; 
        sleep 2; 
    done;
    sleep 2;
    echo
    hamachi get-nicks
#else
    #echo "hamachi is online"
fi

13 June 2010

Run hamachi's tuncfg without being asked for sudo password

It is pretty simple to run tuncfg (required by hamachi) as an ordinary user, and without being asked for password.
Note: I use Ubuntu (9.10 at the moment)

Run in terminal:
sudo visudo

and then append this line:
your-username ALL = NOPASSWD: /sbin/tuncfg

After this you can start tuncfg like this:
sudo tuncfg
and no password prompt will pop-up :)

You should NOT do this if you are worried about security. It is a POTENTIAL security risk.

Hamachi VPN Watchdog (KeepAlive) for Linux (Ubuntu 9.10 and likely 9.04, 10.04, etc.)

UPDATE: there is a new version at http://computarz.blogspot.com/2010/06/updated-hamachi-keep-alive-script.html

I just finished writing a script for keep LogMeIn Hamachi online.

You can get a script for installing and configuring hamachi at: http://www.webupd8.org/2010/05/script-to-install-hamachi-with-gui-in.html
#!/bin/bash

if [ `ip r | grep default -c` -lt 1 ]; then
  # No internet gateway, exiting!
  exit 1
fi

hamachi_online=`hamachi list | egrep '\* [0-9]' | awk '{print $2}'`

me_online=0
for IP in $hamachi_online; do
  ping -c 1 $IP >/dev/null
  if [ $? -eq 0 ]; then me_online=1; break; fi
done

if [ $me_online -eq 0 ]; then
  echo "hamachi is offline - restarting"
  if [ `pgrep -c tuncfg` -eq 0 ]; then sudo /sbin/tuncfg; fi
  hamachi stop >/dev/null
  sleep 1
  for ham_pid in `pgrep -f hamachi -l | grep -v hamachi_watchdog.sh | awk '{print $1}'`; do
      kill -9 ham_pid
  done
  hamachi start
  CNT=1;
  echo -n "Logging in... " ;
  while [ `hamachi login | grep -c failed` -eq 1 -a $CNT -lt 100 ]; do 
      echo -n "$CNT "; 
      let CNT=$CNT+1; 
      sleep 2; 
  done;
  echo
  hamachi get-nicks
#else
  #echo "hamachi is online"
fi
I configured cron to run this script every 5 minutes, by running in terminal:
crontab -e

and then adding this line:
# m h  dom mon dow   command
*/5 * * * * $HOME/bin/hamachi_watchdog.sh

29 February 2008

test for function for counting number of non-zero bits in a 32-bit word

Here's a test for the previous function:
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>

uint32_t count_nonzero_bits(uint32_t n)
{
  uint32_t masks[] = { 0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF };
  size_t i;
  for(i=0; i < 5; i++)
  {
    n = (n & masks[i]) + ((n >> (1 << i)) & masks[i]);
  }
  return n;
}

uint32_t count_nonzero_bits_slow(uint32_t n)
{
  uint32_t cnt=0;
  uint8_t tmp=0;
  while(n>0) {
    tmp = n&1;
    cnt += tmp;
    n >>= 1;
  }
  return cnt;
}

int main() {
  srand(time(0));
  uint32_t iter, X;
  for (iter=0; iter<1000; iter++) {
    X=rand();
    if (count_nonzero_bits(X)!=count_nonzero_bits_slow(X))
      printf("test failed (number=%u)\n", X);
  }
  printf("tests finished\n");
  return 0;
}


enjoy!

Function for counting number of bits set to one, in a 32-bit word (in C)

I've found a great way to (efficiently) count number for bits set to one, in a 32-bit word.

So, here's a function:

uint32_t count_nonzero_bits(uint32_t n)
{
uint32_t masks[] = { 0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF };
for(size_t i=0; i < 5; i++)
{
n = (n & masks[i]) + ((n >> (1 << i)) & masks[i]);
}
return n;
}

It could be easily extended to 64 bits or more, just by adding one (or more) masks.

And here's a link to the original article: http://11011110.livejournal.com/38861.html

22 February 2008

Hamachi on Kubuntu Linux doesn't login... (Logging failed)

I'm a proud user of Hamachi. It's a cross-platform VPN solution:
"Hamachi is a zero-config VPN client for Windows and Linux (currently Beta for Mac). It allows you to, very easily, create a virtual private network that can be logged into and accessed for all over the net. It does this by creating IP tunnels to each VPN client, making them directly accessible to all the other clients on the VPN. Hamachi also encrypts the connections it creates to allow for secure access."
Today, after a long time, I had a problem with it. It couln't login to the Hamachi network. On Linux. On Windows it works fine after few retries (30s or so of retrying...). Therefore, the same mechanism can be used on Linux: retry until success :)

On my Kubuntu Gutsy 7.10, as well as on OpenSuse 10.1, I get the following message:
stomic@dell02:~> hamachi login
Logging in ....>.. failed
stomic@dell02:~> hamachi login
Logging in ....>.. failed
stomic@dell02:~> hamachi login
Logging in ....>.. failed
stomic@dell02:~> hamachi login
Logging in ....>.. failed

But this is boring...
So, I've wrote a one-liner that retries for 100 times, or until a login is successful:
CNT=1; echo -n "Logging in... " ; while [ `hamachi login | grep -c failed` -eq 1 -a $CNT -lt 100 ]; do echo -n "$CNT "; let CNT=$CNT+1; sleep 2; done; echo

You should use this command instead of a simple "hamachi login".
The output is now:

Logging in... 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

You can also make an alias for this command with the bash command:
alias "command"="whatever"

24 August 2007

Strategy DP

this design pattern should: "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."

Consider using it when (one of the following):
  • You have a volatile code that you can separate out of your application for easy maintenance
  • You want to avoid muddling how you handle a task by having to split implementation code over several inherited classes
  • You want to change the algorithm you use for a task at runtime

Decorator DP

This DP allows new/additional behaviour to be added to an existing method of an object dynamically.
The formal definition: "Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality."

The decorator pattern works by wrapping the new "decorator" object around the original object, which is typically achieved by passing the original object as a parameter to the constructor of the decorator, with the decorator implementing the new functionality. The interface of the original object needs to be maintained by the decorator.

Decorators are alternatives to subclassing. Subclassing adds behaviour at compile time whereas decorators provide a new behaviour at runtime.

This difference becomes most important when there are several independent ways of extending functionality. In some object-oriented programming languages, classes cannot be created at runtime, and it is typically not possible to predict what combinations of extensions will be needed at design time. This would mean that a new class would have to be made for every possible combination. By contrast, decorators are objects, created at runtime, and can be combined on a per-use basis. An example of the decorator pattern is the Java I/O Streams implementation.


Factory DP

This DP applies very valuable practice: "Separate the parts of your code that will change the most, from the rest of your applications. And always try to reuse those parts as much as possible".
Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme.
In normal usage, the client software would create a concrete implementation of the abstract factory and then use the generic interfaces to create the concrete objects that are part of the theme.
The client does not know (nor care) about which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products.
This pattern separates the details of implementation of a set of objects from its general usage.

Mediator DP

Let's say you have a four-page web site that lets users browse a store and make purchases. The user should be able to move from randomly from page to page.
Instead of modifying the code in each page to know when and how to jump to every new page and how to activate it, create a mediator class to encapsulate all the navigation code out of the separate pages and place it into a mediator object instead.
From then on, each page just has to report any change of state to the mediator, and the mediator knows what page to send the user to.

Adapter DP

(also called wrapper pattern, or simply wrapper)
You have an upgrade in the system, and the code now needs a new interface. But you already have the code that works with old-type objects.
Now, you create a adapter class that exposes the new interface and calls the already existing methods.
The adapter pattern is useful in situations where an already existing class provides some or all of the services you need but does not use the interface you need.

Proxy DP

Say that you've got some local code that's used to dealing with a local object (only). But, if you want to deal with some remote object, somewhere else in the world.
You create a proxy, a stand-in for another object that makes the local code think it's dealing with a local object. Behind the scenes, the proxy connects to the remote object, all the while making the local code believe it's working with a local object.

19 January 2007

Free Web Hosting - Page 1

Free Web Hosting - Page 1

very nice list of free web servers

search search - grep and less frontend

search
grep and less frontend

This script is used as a frontend to grep & less. Usually, grepping the source code tree for some string doesn't yield a useful output. And it isn't scrollable. So, I've written a simple frontend.

Put it somewhere in your path, and after that you can invoke it in the following way (for example):

The example shown above is for case-insensitive search (-i) in all subdirectories (by default) for a term 'transactCPU'

As a result we get:


Not exactly point-and-click, but much better than original output.

You need to have installed grep and less.

I'm using Kubuntu 6.10 and VIM 7.0

Download here

Good luck!