operator= for a derived class

It didn’t occur to me until now that I have never actually written an operator= for a derived class until now. Or maybe I wasn’t doing it right, or maybe I completely forgot… Here is how you’re supposed to do it:

I don’t ever recall invoking operator=() manually this way. It looks odd, but it should make sense because if you don’t, the base class will never be copied and that’s what you’re explicitly doing.

boost::uuid for unique identifiers

Frequently when I need a unique identifier I might do something silly, like create a static variable and every time an instance of that object is created, I would increment the counter. There are concerns of overflow and other weird things, such as saving and loading these identifiers and syncing the counter back up…

Instead, I would highly recommend using boost::uuid to create a unique identifier. It’s basically a GUID or a UUID. The best part is that it’s cross platform, so it works on mac/linux/windows. It goes something like this:

The syntax is a bit weird for generating a uuid, but that’s how it’s done.

You can use boost::lexical_cast to convert between the uuid and a string. As of right now, boost::serialization can not serialize boost::uuids::uuid objects, for some reason, so the best thing to do is to lexical cast to a string, serialize it, then lexical cast back into a boost::uuids::uuid data type.

Reducing API modifications

A colleague of mind gave me a really cool idea that’s so simple I never thought about it from a design perspective. Sometimes, a function might take several arguments, where each argument represents a configuration value.

If, in the future, you need to add more settings you can add more parameters… But that causes the API to change, which is a huge hassle most of the time. Instead, it’s better to create a struct and pass that in. That way, the API is kept the same. You probably want to initialize the struct to some good defaults though.

So now, it doesn’t matter how many settings you might add in the future, the API doesn’t change. In fact, if you look at the Win32 API, you’ll see they do the same thing. The function takes a struct, and a bunch of stuff you need to set in the struct. This allows the API to be usable well after it should be be killed without the older apps crashing. 🙂

Comments – 01

I think the APIs should be most self documenting. So I prefer to not add any comments unless it somehow helps. Obviously, this doesn’t help if the user wants doxygen documentation. If you do add comments, they should be in the .cpp file only. The reason for this is because reading the .h file is nice, neat, and compact. Otherwise, your header files are massively huge and difficult to digest. But if you do need comments, make sure they’re doxygen style.

So in the cpp file, prefer to have something like this:

There’s no point in adding comments to this function because it should be obvious. But I prefer to have the divider for readability. If you need comments, add them doxygen style, like this:

This of course causes problems. If all of your function comments are in the cpp, you need the cpp to read the documentation. This is okay for me, but not okay if someone else uses the library precompiled. But then again, you’re probably going to have to compile the sources yourself anyways since there’s no guarantee the ABI won’t change between versions of the tool chain.

This is a catch 22. You must build doxygen comments in order to see the documentation. Or ship the source code. I really don’t care because I don’t intend on publishing any of my code… Right now anyways. But I’m not sure if it would make my life easier just putting them all in the .h file.

Linux Quick Reference

General Sys Admin
Misc Commands
uname -r – Displays kernel version
useful for changing between bases – calculator: bc; obase=#; ibase=#; input base # and output base #
editing the runlevel /etc/inittab
changing the runlevel on the fly: init #
Get version of ubuntu: lsb_release -a

Hardware Information
network settings: /sbin/ifconfig -a
displays cpu info: cat /proc/cpuinfo
displays devices: cat /proc/devices
list hardware: /sbin/lspci -vv
displays system status: procinfo -a
free memory: free -m
checks hard drive specs: hdparm -I /dev/device
lspci -nn – Shows hardware connected to the pci bus
lsusb – Shows USB connected hardware
lshw -C usb – Additional info on USB related hardware (good for USB dongles)
cat /proc/cpuinfo
cat /proc/meminfo
cat /proc/zoneinfo
cat /proc/mounts

File / Drive / Directory Commands
pwd – print working directory
check file or directory size: du -sh filename
get partition information: df -alh
mount a drive: mount -t dos floppy /dev/fd0
find something: apropos or whatis, which, locate (updatedb), whereis, find / -print | xargs grep
zip up a folder: tar czf filename.tar.gz folder
unzip a folder: tar -zxvf filename.tar.gz
Download a file: scp @:
Upload a file: scp @:

Process Management
ps -aux | grep program_name
list processes: ps -eflea
list processes interactively: top or htop
identify processes using files or sockets: fuser filename
run a process in the the background after logging off: nohup command & OR command &
atq : views the pending jobs
watch PROGRAM_NAME – keeps running the same program over and over
crontab -l : Displays crontab jobs
crontab -e : Edits the crontab job file
at : schedules a one time task
batch : runs a task when the system load average is low

top : interactive process management
t: Displays summary information off and on.
m : Displays memory information off and on.
A: Sorts the display by top consumers of various system resources. Useful for quick identification of performance-hungry tasks on a system.
f: Enters an interactive configuration screen for top. Helpful for setting up top for a specific task.
o: Enables you to interactively select the ordering within top.
r: Issues renice command.
k: Issues kill command.
z: Turn on or off color/mono

User Management
who – Who is connected to the machine
last – last users who’ve logged in
rwho -a

Service Management
service status | start | stop | restart
sudo /etc/init.d/service-name (start|stop|restart)
/usr/sbin/ntsysv : allows you to modify system services
/usr/sbin/chkconfig : allows you to modify system services
/sbin/chkconfig –list : lists systems services and their state
service –status-all

Package Management
apt-get install : Installs package
apt-get remove : Removes package
apt-get –purge remove : Removes package & configuration files
apt-get update : Updates the the package listings from the mirrors on the servers
apt-get upgrade : Displays list of upgrades for package
apt-get dist-upgrade : Similar to apt-get upgrade, except will install or remove packages to satisfy dependencies
apt-cache search “TextToSearch” : Searches description and package names for a keyword
Ex: apt-cache search “Intrusion Detection”
Ex2: apt-cache search sniffer
apt-cache depends : Lists package dependencies
apt-cache showpkg : Shows more details about the package
apt-cache show : Same as dpkg -s

dpkg -l : Lists all installed packages
dpkg -l : Lists individual package
dpkg -l ‘**’ : Lists packages related to dpkg -L : Lists files owned by the installed package
dpkg — contents sudo_1.6.7p5-2_i386.deb : Lists files owned by not installed package
dpkg -S /bin/netstat : Finds what package owns the /bin/netstat file
dpkg -s | grep Status : Checks if package is installed or not
dpkg -s : Lists lots of info about the package installed

Networking Commands
ifconfig – lists IP address (similar to ipconfig in Windows)
/etc/rc.d/init.d/network start – start the network service
sudo ifconfig up/down – Brings up/down the interface for the specified interface
/etc/init.d/network restart – restarts the interfaces
activating your NIC: /sbin/ifup eth0 or ifconfig eth0 up
deactivating your NIC: /sbin/ifdown eth0 or ifconfig eth0 down

sudo dhclient – Request IP address from DNS server for specified interface
sudo dhclient -r – Release IP address associated with specified interface
sudo iptables -L – Lists firewall rules
/etc/iftab (Feisty and pre-releases (Edgy, etc)) – /etc/udev/rules.d/70-persistent-net.rules (Gutsy) – File which assigns logical names (eth0, wlan0, etc) to MAC addresses
cat /etc/resolv.conf – Lists DNS servers associated with network connections (Network Manager)
/etc/dhcp3/dhclient.conf – File which sets or modifies dns (domain name servers) settings

Lists open ports:
lsof -Pnl +M -i4 : Lists open ports
lsof -Pnl +M -i6 : Lists open ports
-P : This option inhibits the conversion of port numbers to port names for network files. Inhibiting the conver-
sion may make lsof run a little faster. It is also useful when port name lookup is not working properly.
-n : This option inhibits the conversion of network numbers to host names for network files. Inhibiting conversion may make lsof run faster. It is also useful when host name lookup is not working properly.
-l : This option inhibits the conversion of user ID numbers to login names. It is also useful when login name lookup is working improperly or slowly.
+M : Enables the reporting of portmapper registrations for local TCP and UDP ports.
-i4 : IPv4 listing only
-i6 : IPv6 listing only

cat /proc/net/tcp |perl -lane ‘(undef,$p)=split “:”,$F[1]; print hex($p).”\t”.getpwuid($F[7]) if $p’|sort -n|uniq -c
netstat -tulpn
netstat -npl
-t : TCP port
-u : UDP port
-l : Show only listening sockets.
-p : Show the PID and name of the program to which each socket / port belongs
-n : No DNS lookup (speed up operation)

Shows service listening on port 8080:
cat /etc/services | grep 8080

route -n OR netstat -rn : Shows current gateway
Check routing cache: /sbin/route -Cn
route : shows/modifies current routing table
nslookup www.address.com or dig www.address.com – shows info about the server’s ip
iwlist scan – shows wireless networks that are available in the area along with basic encryption information
lshw -C network – Shows interface and driver associated with each networking device
sudo route add default gw – Example of how to set the default gateway to
sudo route del default gw – Example of how to delete the default gateway setting
mtr – my traceroute
change finger information: chfn
talk username [terminal-name]
write username [terminal-name] – must be using the same computer
arp -e : shows other systems’ MAC addresses
cat /proc/net/arp : shows current arp table
iptables, ipchains(old)
socklist : lists open sockets,type,port, process id and name, use fuser or kill
host : same as nslookup but will use both hosts file as well as DNS
nslookup : returns an ip address give a hostname
netstat – displays connections, routing tables, stats, etc.
netstat -punta : list externally connected processes
netstat -nap : list all connected processes
netstat -s : show network stastics
netstat -a -i eth0 :kernel interface table info
iptraf – program for monitoring lan traffic
tcpdump – allows you to analyze certain packets based on a criteria
nmap -sP : scans network for pingable ip addresses
Wireshark – network protocol analyzer

important files:
Environment Variables
To make environment variables set themselves at every login
place them in .bash_profile in the user’s home directory

– To add to an already existing one
export PATH

– To Create a new one
export PATH
check environment variables: set, env

– To reload the .bash_profile type:
source ~/.bash_profile

Common process kill signals:
SIGHUP – the modem connection has been broken
SIGQUIT – the process should stop and produce a coredump file as a debugging aid
SIGINT – the user has struck the interrupt key (^C)
SIGKILL – signal 9
SIGTERM – the default termination signal sent by kill

Octal Permissions
read: 4
write: 2

Sections of the Manual
man pages sections: man # command
1) Commands
2) System Calls
3) Library Functions
4) Special Files
5) File Formats
6) Games
7) Miscellaneous Information
8) Maintenance Commands

SVN Client Commands
checkout: svn co svn://hostname/myproject myproject
update: svn update
svnserve -d –foreground -r /home/svn

Module and kernel manipulation
1) list loaded modules: /sbin/lsmod
2) Determines if the module is compatable with the kernel
High level handling of loadable modules
Loads module and dependencies : modprobe module
3) Remove a loaded module: /sbin/rmmod modulename
4) Inserts a module into the active kernel: /sbin/insmod modulename
5) Creates dependencies file for a module (used by modprobe): depmod
6) Display information about a kernel module: modinfo
cat /etc/modprobe.d/blacklist – List modules that will not be loaded by the Operating System at boot time
lsmod – lists currently loaded kernel modules. (Example usage – lsmod | grep ndiswrapper)
sudo modprobe ***** – Loads the kernel module **** . (Example usage – sudo modprobe ndiswrapper, sudo modprobe r818x, sudo modprobe ath_pci)
sudo modprobe -r **** – Unloades the kernel module ****. (Example usage – sudo modprobe -r ndiswrapper)
dmesg | more – Lists boot log \u2014 good for troubleshooting problems with modules/drivers not being loaded

XWindow Commands
xorgcfg – Graphical configuration tool for XFree86 4.0
X -configure – generate an XF86Config file
glxgears – displays an openGL demo app
xvidtune – allows you to adjust monitor and graphics properties
how to restart xfree86 server and client:
shut down X11: sudo killall gdm or init 3
start with: init 5
Important XWindow Files:
Specifies which window manager to use and what
applications to start: $HOME/.xinitrc
Same as above: $HOME/.xsession
X Window Display Manager, automatically starts the xserver: xdm
$HOME/.Xdefaults: resources are stored here

logging into an ssh server: ssh username@ipaddress
starting a vncserver: vncserver
killing a vncserver: vncserver -k :# (where # is the display number created when you started the server)
getting regular desktop: modify the $HOME/.vnc/xstartup file
Download a file: scp @:

Printer Management
http://localhost:631 – used to manage cups – use root as the login
Current Printer Description from CUPS management webpage:
hppsc1510 (Default Printer)
Description: HP PSC 1510 All-In-One
Location: HP PSC 1510 All-In-One
Make and Model: HP PSC 1510 Foomatic/hpijs (recommended)
Printer State: idle, accepting jobs, published.
Device URI: hp:/usb/PSC_1500_series?serial=MY62ND30C90498

Open ports 50000 and 50002 in the firewall. Check /var/log/messages to verify.
Getting network printing to work from windows
Make sure the “hplip” service is running to take advantage of all the features
1) Install HP Printer on windows machine using normal USB cable
2) Install HP Printer on linux machine using normal USB cable using the hplip driver and CUPS
3) Set up samba and CUPS together.
4) Browse to My Network Places and make sure the printer is in there.
Double click it (connect to it) and install the HP PSC 950 ( or something ) driver.
5) After the driver is installed, go into “Printers and Faxes” and make sure it is
in there.
6) Right click on it and go to properties->advanced and select the correct driver (HP PSC 1510 driver)
7) Click on “Color Management” and add all the HP_PSC_1600…. files. Also add the “sRGB Color Space Profile”

Other common ops:
Send a file to the printer: lpr or lp
Shows print jobs in queue: lpq or lpstat
Cancel print job: lprm or cancel
Installing sun Java on ubuntu 11.04
sudo add-apt-repository ppa:ferramroberto/java OR sudo add-apt-repository “deb http://archive.canonical.com/ lucid partner”
sudo apt-get update
sudo apt-get install sun-java6-bin sun-java6-jre sun-java6-jdk
sudo update-java-alternatives -s java-6-sun
ls /usr/lib/jvm -> To find out which one you need (just use the generic link)
sudo bash -c “echo JAVA_HOME=/usr/lib/jvm/java-6-sun/ >> /etc/environment”
Add : $JAVA_HOME/bin to the /etc/environment file under the path file.
java -version

Logging into mysql: mysql -u root -p
Restart mysql: “mysqld restart”

mysql commands:
show tables;
show databases;

Set up so you don’t have to type in password

On the client machine that gets prompted for the password when you attempt to scp, do the following:

cd ssh-keygen -t rsa
scp /root/.ssh/id_rsa.pub ::/home//id_rsa.pub2 (otherwise rename it to pub2 so it doesn’t overwrite the one on the server)
ssh @
cd /root/.ssh
cat /root/.ssh/id_rsa.pub2 >> authorized_keys
Delete the id_rsa.pub2 file when you are done.

Ubuntu Firewall
ufw enable
ufw disable