wireshark command line capture

tethereal -i eth0 -w mycapture.pcap

sending SIGTERM or SIGINT (ctrl-c) will cause it to exit cleanly.

Serial Port in Linux

stty


stty -F /dev/ttyS10 
stty -F /dev/ttyS10 -a
stty -F /dev/ttyS10 230400 crtscts
stty -F /dev/ttyS10 230400 -crtscts
http://www.armadeus.com/wiki/index.php?title=Serial_ports_usage_on_Linux

minicom


minicom -s

minicom ttys10  (ttys10 is a saved config)

ctrl-a q (quit)
ctrl-a o (config)
ctrl-z (help)

screen


screen /dev/ttyS10 115200 
screen /dev/ttyS10 115200,crtscts 

ctrl-a K  (kill)
ctrl-a d  (detach)
ctrl-a i  (status)

$ sudo screen -ls
There are screens on:
        7578.pts-0.fedora (Detached)
        7575.pts-0.fedora (Detached)
        2009.pts-0.fedora (Detached)
$ sudo screen -r 7578 -X kill
$ sudo screen -r 7575 -X kill
$ sudo screen -r 2009 -X kill
$ sudo screen -ls
# copy and paste
C-a : bufferfile /etc/passwd
C-a < C-a ]
C-a : bufferfile
No Sockets found in /var/run/screen/S-root.

MFC 495CW Printer Setup on Fedora 17

Download and install the following:
mfc495cwlpr-1.1.2-1.i386.rpm
mfc495cwcupswrapper-1.1.2-2.i386.rpm
Then copy the file brlpdwrappermfc495cw to /usr/lib/cups/filter/. Don't remember where it comes but had a copy from my old machine:
$ cat packages/brother/brlpdwrappermfc495cw 
#! /bin/sh
#
# Copyright (C) 2005 Brother. Industries, Ltd.
#                                    Ver1.10

# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307  USA
#

LOGFILE="/dev/null"
LOGLEVEL="1"
LOGCLEVEL="7"
DEBUG=0
NUPENABLE=1
LOG_LATESTONLY=1
errorcode=0

if [ $DEBUG != 0 ]; then
    LOGFILE=/tmp/br_cupsfilter_debug_log
fi

PPDC=`printenv | grep "PPD="`
PPDC=`echo $PPDC | sed -e 's/PPD=//'`

if [ "$PPDC" = "" ]; then
    PPDC="/usr/share/cups/model/brmfc495cw.ppd"
fi


if [ $LOGFILE != "/dev/null" ]; then
  if [ $LOG_LATESTONLY == "1" ]; then
    rm -f $LOGFILE
    date                                                           >$LOGFILE
  else
    if [ -e $LOGFILE ]; then
     date                                                        >>$LOGFILE
    else
     date                                                        >$LOGFILE
    fi
  fi
    echo "arg0 = $0"                                           >>$LOGFILE
    echo "arg1 = $1"                                           >>$LOGFILE
    echo "arg2 = $2"                                           >>$LOGFILE
    echo "arg3 = $3"                                           >>$LOGFILE
    echo "arg4 = $4"                                           >>$LOGFILE
    echo "arg5 = $5"                                           >>$LOGFILE
    echo "arg6 = $6"                                           >>$LOGFILE
    echo "PPD  = $PPD"                                         >>$LOGFILE
fi

INPUT_TEMP_PS=`mktemp /tmp/br_input_ps.XXXXXX`

nup="cat"
if [ "" != '' ] && [ $NUPENABLE != 0 ]; then

 if   [ "" != '' ]; then
  nup="psnup -64"
 elif [ "" != '' ]; then
  nup="psnup -32"
 elif [ "" != '' ]; then
  nup="psnup -25"
 elif [ "" != '' ]; then
  nup="psnup -16"
 elif [ "" != '' ]; then
  nup="psnup -8"
 elif [ "" != '' ]; then
  nup="psnup -6"
 elif [ "" != '' ]; then
  nup="psnup -4"
 elif [ "" != '' ]; then
  nup="psnup -2"
 elif [ "" != '' ]; then
  nup="cat"
 fi
 echo   "NUP=$nup"                                      >>$LOGFILE
   if [ -e /usr/bin/psnup ]; then
       if [ $# -ge 7 ]; then
        cat $6  | $nup > $INPUT_TEMP_PS
       else
        cat       | $nup > $INPUT_TEMP_PS
       fi
   else
       if [ $# -ge 7 ]; then
        cp $6  $INPUT_TEMP_PS
       else
        cat    > $INPUT_TEMP_PS
       fi
   fi
else
   if [ $# -ge 7 ]; then
      cp $6  $INPUT_TEMP_PS
   else
      cat    > $INPUT_TEMP_PS
   fi
fi
if [ -e "/usr/local/Brother/Printer/mfc495cw/lpd/filtermfc495cw" ]; then
       :
else
    echo "ERROR: /usr/local/Brother/Printer/mfc495cw/lpd/filtermfc495cw does not exist"   >>$LOGFILE
    errorcode=30
    exit
fi

CUPSOPTION=`echo "$5 Copies=$4" | sed -e 's/BrMirror=OFF/MirrorPrint=OFF/' -e 's/BrMirror=ON/MirrorPrint=ON/' -e 's/BrChain/Chain/' -e 's/BrBrightness/Brightness/' -e 's/BrContrast/Contrast/' -e 's/BrHalfCut/HalfCut/' -e 's/BrAutoTapeCut/AutoCut/' -e 's/BrHalftonePattern/Halftone/' -e 's/Binary/Binary/' -e 's/Dither/Dither/' -e 's/ErrorDiffusion/ErrorDiffusion/' -e 's/PageSize/media/' -e 's/BrSheets/Sheets/' -e 's/multiple-document-handling/Collate/' -e 's/separate-documents-collated-copies/ON/' -e 's/separate-documents-uncollated-copies/OFF/'`
if [ -e "/usr/local/Brother/Printer/mfc495cw/cupswrapper/brcupsconfpt1" ]; then
  if [ $DEBUG = 0 ]; then
     /usr/local/Brother/Printer/mfc495cw/cupswrapper/brcupsconfpt1  MFC495CW  $PPDC 0 "$CUPSOPTION" "mfc495cw">> /dev/null
  else
     /usr/local/Brother/Printer/mfc495cw/cupswrapper/brcupsconfpt1  MFC495CW  $PPDC $LOGCLEVEL "$CUPSOPTION" "mfc495cw">>$LOGFILE
  fi
fi

if [ $DEBUG -lt 10 ]; then
    cat    $INPUT_TEMP_PS | /usr/local/Brother/Printer/mfc495cw/lpd/filtermfc495cw "$$" "CUPS" "USB"

    if [ $LOGLEVEL -gt 2 ];  then
    if [ $LOGFILE != "/dev/null" ]; then
      echo ""                                                >>$LOGFILE
      echo "    ------PostScript Data-------"                >>$LOGFILE
      cat    $INPUT_TEMP_PS                                  >>$LOGFILE
    fi
    fi
fi
rm -f  $INPUT_TEMP_PS

exit 
also see http://en.gentoo-wiki.com/wiki/Brother_Mfc-495cw

udevadm

 $ udevadm info -q path -n /dev/sdc
/devices/pci0000:00/0000:00:1c.4/0000:04:00.0/usb4/4-2/4-2:1.0/host10/target10:0:0/10:0:0:0/block/sdc
[jshih@i7 ~]$ udevadm info -a -p  $(udevadm info -q path -n /dev/sdc)

Udevadm info starts with the device specified by the devpath and then
walks up the chain of parent devices. It prints for every device
found, all possible attributes in the udev rules key format.
A rule to match, can be composed by the attributes of the device
and the attributes from one single parent device.

  looking at device '/devices/pci0000:00/0000:00:1c.4/0000:04:00.0/usb4/4-2/4-2:1.0/host10/target10:0:0/10:0:0:0/block/sdc':
    KERNEL=="sdc"
    SUBSYSTEM=="block"
    DRIVER==""
    ATTR{ro}=="0"
    ATTR{size}=="976773168"
    ATTR{stat}=="    1172       43     9062     4975        0        0        0        0        0     1307     4974"
    ATTR{range}=="16"
    ATTR{discard_alignment}=="0"
    ATTR{events}==""
    ATTR{ext_range}=="256"
    ATTR{events_poll_msecs}=="-1"
    ATTR{alignment_offset}=="0"
    ATTR{inflight}=="       0        0"
    ATTR{removable}=="0"
    ATTR{capability}=="50"
    ATTR{events_async}==""

  looking at parent device '/devices/pci0000:00/0000:00:1c.4/0000:04:00.0/usb4/4-2/4-2:1.0/host10/target10:0:0/10:0:0:0':
    KERNELS=="10:0:0:0"
    SUBSYSTEMS=="scsi"
    DRIVERS=="sd"
    ATTRS{rev}=="0001"
    ATTRS{type}=="0"
    ATTRS{scsi_level}=="0"
    ATTRS{model}=="3AS             "
    ATTRS{state}=="running"
    ATTRS{queue_type}=="none"
    ATTRS{iodone_cnt}=="0x4eb"
    ATTRS{iorequest_cnt}=="0x4eb"
    ATTRS{timeout}=="30"
    ATTRS{evt_media_change}=="0"
    ATTRS{max_sectors}=="240"
    ATTRS{ioerr_cnt}=="0x7"
    ATTRS{queue_depth}=="1"
    ATTRS{vendor}=="ST950042"
    ATTRS{device_blocked}=="0"
    ATTRS{dh_state}=="detached"
    ATTRS{iocounterbits}=="32"

  looking at parent device '/devices/pci0000:00/0000:00:1c.4/0000:04:00.0/usb4/4-2/4-2:1.0/host10/target10:0:0':
    KERNELS=="target10:0:0"
    SUBSYSTEMS=="scsi"
    DRIVERS==""

  looking at parent device '/devices/pci0000:00/0000:00:1c.4/0000:04:00.0/usb4/4-2/4-2:1.0/host10':
    KERNELS=="host10"
    SUBSYSTEMS=="scsi"
    DRIVERS==""

  looking at parent device '/devices/pci0000:00/0000:00:1c.4/0000:04:00.0/usb4/4-2/4-2:1.0':
    KERNELS=="4-2:1.0"
    SUBSYSTEMS=="usb"
    DRIVERS=="usb-storage"
    ATTRS{bInterfaceClass}=="08"
    ATTRS{bInterfaceSubClass}=="06"
    ATTRS{bInterfaceProtocol}=="50"
    ATTRS{bNumEndpoints}=="02"
    ATTRS{supports_autosuspend}=="1"
    ATTRS{bAlternateSetting}==" 0"
    ATTRS{bInterfaceNumber}=="00"

  looking at parent device '/devices/pci0000:00/0000:00:1c.4/0000:04:00.0/usb4/4-2':
    KERNELS=="4-2"
    SUBSYSTEMS=="usb"
    DRIVERS=="usb"
    ATTRS{bDeviceSubClass}=="00"
    ATTRS{bDeviceProtocol}=="00"
    ATTRS{devpath}=="2"
    ATTRS{idVendor}=="174c"
    ATTRS{speed}=="5000"
    ATTRS{bNumInterfaces}==" 1"
    ATTRS{bConfigurationValue}=="1"
    ATTRS{bMaxPacketSize0}=="9"
    ATTRS{busnum}=="4"
    ATTRS{devnum}=="2"
    ATTRS{configuration}==""
    ATTRS{bMaxPower}=="  0mA"
    ATTRS{authorized}=="1"
    ATTRS{bmAttributes}=="c0"
    ATTRS{bNumConfigurations}=="1"
    ATTRS{maxchild}=="0"
    ATTRS{bcdDevice}=="0100"
    ATTRS{avoid_reset_quirk}=="0"
    ATTRS{quirks}=="0x0"
    ATTRS{serial}=="0123456789ABCDEF"
    ATTRS{version}==" 3.00"
    ATTRS{urbnum}=="3770"
    ATTRS{ltm_capable}=="no"
    ATTRS{manufacturer}=="ASMedia"
    ATTRS{removable}=="unknown"
    ATTRS{idProduct}=="55aa"
    ATTRS{bDeviceClass}=="00"
    ATTRS{product}=="AS2105"

  looking at parent device '/devices/pci0000:00/0000:00:1c.4/0000:04:00.0/usb4':
    KERNELS=="usb4"
    SUBSYSTEMS=="usb"
    DRIVERS=="usb"
    ATTRS{bDeviceSubClass}=="00"
    ATTRS{bDeviceProtocol}=="03"
    ATTRS{devpath}=="0"
    ATTRS{idVendor}=="1d6b"
    ATTRS{speed}=="5000"
    ATTRS{bNumInterfaces}==" 1"
    ATTRS{bConfigurationValue}=="1"
    ATTRS{bMaxPacketSize0}=="9"
    ATTRS{authorized_default}=="1"
    ATTRS{busnum}=="4"
    ATTRS{devnum}=="1"
    ATTRS{configuration}==""
    ATTRS{bMaxPower}=="  0mA"
    ATTRS{authorized}=="1"
    ATTRS{bmAttributes}=="e0"
    ATTRS{bNumConfigurations}=="1"
    ATTRS{maxchild}=="2"
    ATTRS{bcdDevice}=="0306"
    ATTRS{avoid_reset_quirk}=="0"
    ATTRS{quirks}=="0x0"
    ATTRS{serial}=="0000:04:00.0"
    ATTRS{version}==" 3.00"
    ATTRS{urbnum}=="96"
    ATTRS{ltm_capable}=="no"
    ATTRS{manufacturer}=="Linux 3.6.7-4.fc17.x86_64 xhci_hcd"
    ATTRS{removable}=="unknown"
    ATTRS{idProduct}=="0003"
    ATTRS{bDeviceClass}=="09"
    ATTRS{product}=="xHCI Host Controller"

  looking at parent device '/devices/pci0000:00/0000:00:1c.4/0000:04:00.0':
    KERNELS=="0000:04:00.0"
    SUBSYSTEMS=="pci"
    DRIVERS=="xhci_hcd"
    ATTRS{irq}=="42"
    ATTRS{subsystem_vendor}=="0x1458"
    ATTRS{broken_parity_status}=="0"
    ATTRS{class}=="0x0c0330"
    ATTRS{consistent_dma_mask_bits}=="32"
    ATTRS{dma_mask_bits}=="64"
    ATTRS{local_cpus}=="00000000,00000000,00000000,000000ff"
    ATTRS{device}=="0x7023"
    ATTRS{msi_bus}==""
    ATTRS{local_cpulist}=="0-7"
    ATTRS{vendor}=="0x1b6f"
    ATTRS{subsystem_device}=="0x5007"
    ATTRS{numa_node}=="-1"
    ATTRS{d3cold_allowed}=="1"

  looking at parent device '/devices/pci0000:00/0000:00:1c.4':
    KERNELS=="0000:00:1c.4"
    SUBSYSTEMS=="pci"
    DRIVERS=="pcieport"
    ATTRS{irq}=="16"
    ATTRS{subsystem_vendor}=="0x1458"
    ATTRS{broken_parity_status}=="0"
    ATTRS{class}=="0x060400"
    ATTRS{consistent_dma_mask_bits}=="32"
    ATTRS{dma_mask_bits}=="32"
    ATTRS{local_cpus}=="00000000,00000000,00000000,000000ff"
    ATTRS{device}=="0x1c18"
    ATTRS{msi_bus}=="1"
    ATTRS{local_cpulist}=="0-7"
    ATTRS{vendor}=="0x8086"
    ATTRS{subsystem_device}=="0x5001"
    ATTRS{numa_node}=="-1"
    ATTRS{d3cold_allowed}=="0"

  looking at parent device '/devices/pci0000:00':
    KERNELS=="pci0000:00"
    SUBSYSTEMS==""
    DRIVERS==""

[jshih@i7 ~]$ udevadm info -q path -n /dev/sdc
/devices/pci0000:00/0000:00:1c.4/0000:04:00.0/usb4/4-2/4-2:1.0/host10/target10:0:0/10:0:0:0/block/sdc
[jshih@i7 ~]$ udevadm info -q env -n /dev/sdc
DEVLINKS=/dev/disk/by-id/ata-ST9500423AS_6WR0N60Q /dev/disk/by-id/wwn-0x5000c5004a982eb5 /dev/disk/by-path/pci-0000:04:00.0-usb-0:2:1.0-scsi-0:0:0:0
DEVNAME=/dev/sdc
DEVPATH=/devices/pci0000:00/0000:00:1c.4/0000:04:00.0/usb4/4-2/4-2:1.0/host10/target10:0:0/10:0:0:0/block/sdc
DEVTYPE=disk
ID_ATA=1
ID_ATA_DOWNLOAD_MICROCODE=1
ID_ATA_FEATURE_SET_APM=1
ID_ATA_FEATURE_SET_APM_CURRENT_VALUE=128
ID_ATA_FEATURE_SET_APM_ENABLED=1
ID_ATA_FEATURE_SET_HPA=1
ID_ATA_FEATURE_SET_HPA_ENABLED=1
ID_ATA_FEATURE_SET_PM=1
ID_ATA_FEATURE_SET_PM_ENABLED=1
ID_ATA_FEATURE_SET_SECURITY=1
ID_ATA_FEATURE_SET_SECURITY_ENABLED=0
ID_ATA_FEATURE_SET_SECURITY_ENHANCED_ERASE_UNIT_MIN=96
ID_ATA_FEATURE_SET_SECURITY_ERASE_UNIT_MIN=96
ID_ATA_FEATURE_SET_SMART=1
ID_ATA_FEATURE_SET_SMART_ENABLED=1
ID_ATA_ROTATION_RATE_RPM=7200
ID_ATA_SATA=1
ID_ATA_SATA_SIGNAL_RATE_GEN1=1
ID_ATA_SATA_SIGNAL_RATE_GEN2=1
ID_ATA_WRITE_CACHE=1
ID_ATA_WRITE_CACHE_ENABLED=1
ID_BUS=ata
ID_MODEL=ST9500423AS
ID_MODEL_ENC=ST9500423AS\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20
ID_PART_TABLE_TYPE=dos
ID_PATH=pci-0000:04:00.0-usb-0:2:1.0-scsi-0:0:0:0
ID_PATH_TAG=pci-0000_04_00_0-usb-0_2_1_0-scsi-0_0_0_0
ID_REVISION=0001SD5M
ID_SERIAL=ST9500423AS_6WR0N60Q
ID_SERIAL_SHORT=6WR0N60Q
ID_TYPE=disk
ID_WWN=0x5000c5004a982eb5
ID_WWN_WITH_EXTENSION=0x5000c5004a982eb5
MAJOR=8
MINOR=32
SUBSYSTEM=block
TAGS=:systemd:
UDISKS_ATA_SMART_IS_AVAILABLE=1
UDISKS_PARTITION_TABLE=1
UDISKS_PARTITION_TABLE_COUNT=12
UDISKS_PARTITION_TABLE_SCHEME=mbr
UDISKS_PRESENTATION_NOPOLICY=0
USEC_INITIALIZED=966774215

Create Fedora Installation USB with Live USB Creator

Download the Fedora-DVD.iso and install liveusb-creator.noarch. Start the Live USB Creator and browse the iso file.

i7 2600k temperature @ 3.7Ghz on F17

On Fedora 17.

idle


[root@i7 ~]# cat /proc/cpuinfo |grep MH
cpu MHz  : 1600.000
cpu MHz  : 1600.000
cpu MHz  : 1600.000
cpu MHz  : 1600.000
cpu MHz  : 1600.000
cpu MHz  : 1600.000
cpu MHz  : 1600.000
cpu MHz  : 1600.000
[root@i7 ~]# sensors
coretemp-isa-0000
Adapter: ISA adapter
Physical id 0:  +34.0°C  (high = +80.0°C, crit = +98.0°C)
Core 0:         +27.0°C  (high = +80.0°C, crit = +98.0°C)
Core 1:         +31.0°C  (high = +80.0°C, crit = +98.0°C)
Core 2:         +34.0°C  (high = +80.0°C, crit = +98.0°C)
Core 3:         +30.0°C  (high = +80.0°C, crit = +98.0°C)

fully loaded


$ cat /proc/cpuinfo |grep MH
cpu MHz  : 3701.000
cpu MHz  : 3701.000
cpu MHz  : 3701.000
cpu MHz  : 3701.000
cpu MHz  : 3701.000
cpu MHz  : 3701.000
cpu MHz  : 3701.000
cpu MHz  : 3701.000


$ sensors
coretemp-isa-0000
Adapter: ISA adapter
Physical id 0:  +60.0°C  (high = +80.0°C, crit = +98.0°C)
Core 0:         +56.0°C  (high = +80.0°C, crit = +98.0°C)
Core 1:         +56.0°C  (high = +80.0°C, crit = +98.0°C)
Core 2:         +61.0°C  (high = +80.0°C, crit = +98.0°C)
Core 3:         +56.0°C  (high = +80.0°C, crit = +98.0°C)

tar with pigz

tar -cpvf mydata.tar.gz -I pigz -C path dir

Protobuf Examples C++ and Java (2)

This sample .proto is taken from http://www.indelible.org/ink/protobuf-polymorphism/. Also see example 1

animal.proto


 package animal;

option java_outer_classname = "Animals";

message Cat
{
    optional bool declawed = 1;
}

message Dog
{
    optional uint32 bones_buried = 1;
}

message Animal
{
    required float weight = 1;
    optional Dog dog = 2;
    optional Cat cat = 3;
}

animal.cpp


#include 
#include "animal.pb.h"
using namespace std;
using namespace animal;

int main()
{
  Cat cat1;
  cat1.set_declawed(true);

  Animal animal;
  animal.set_weight(10.4);
  Cat* cat = animal.mutable_cat();

  cat->set_declawed(true);


  Dog *dog = animal.mutable_dog();
  dog->set_bones_buried (32);

  string s;
  animal.SerializeToString(&s);

  Animal animal2;

  animal2.ParseFromString(s);

  printf("weight %f\n", animal2.weight());

  if (animal.has_cat())
  {
    printf("cat %d\n", animal.cat().declawed());
  }

  if (animal.has_dog())
  {
    printf("dog %d\n", animal.dog().bones_buried());
  }

  return 0;
} 

animal.java


import animal.Animals;
import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.ExtensionRegistry;
import com.google.protobuf.*;
import java.io.IOException;

 
class AnimalExample {

 
    public static void main(String[] args) throws Exception {

        Animals.Animal animal =  Animals.Animal.newBuilder().
            setWeight(10.4F)
            .setDog(Animals.Dog.newBuilder().setBonesBuried(32).build())
            .setCat(Animals.Cat.newBuilder().setDeclawed(true).build())
            .build();
        
        

        byte[] data = animal.toByteArray();

        Animals.Animal animal2 = Animals.Animal.newBuilder().mergeFrom(data).build();
        
        System.out.println("Animal weight " + animal2.getWeight());

        if (animal2.hasCat()) {

            System.out.println("Cat " + animal2.getCat().getDeclawed());
        }

        if (animal2.hasDog()){
            System.out.println("Dog " + animal2.getDog().getBonesBuried());
        }
    }
    
}
 

Protobuf Examples for C++ and Java (1)

This sample .proto is taken from http://blog.wolfman.com/articles/2011/11/23/how-to-implement-polymorphic-protocol-buffers-in-java. The groovy is rewritten in Java and C++. Also see example 2

example.proto


package example;

option java_outer_classname = "Commands";

message BaseCommand {
        extensions 100 to max;

        enum CommandType {
                VERSION = 1;
                LOGIN   = 2;
        }
        required CommandType type = 1;
}


message Version {
        extend BaseCommand {
                required Version cmd = 100;
        }

        required fixed32 protocol = 1;
        required fixed32 versions = 2;
}

message Login {
        extend BaseCommand {
                required Login cmd = 101;
        }
        required string username = 1;
        required string password = 2;
}

example.cpp


#include 
#include "example.pb.h"
using namespace std;
using namespace example;

int main()
{
  string sl;


  BaseCommand b;


#if 0
  Version ver;
  ver.set_versions(10);
  ver.set_protocol(15);

  
  b.MutableExtension(Version::cmd)->set_versions(10);
  b.MutableExtension(Version::cmd)->set_protocol(15);

  b.set_type( BaseCommand::VERSION);
#else
  b.set_type( BaseCommand::LOGIN);

  b.MutableExtension(Login::cmd)->set_username("rain");
  b.MutableExtension(Login::cmd)->set_password("heavy");
  

#endif
  b.SerializeToString(&sl);


  printf("%d\n", sl.length());

  BaseCommand* bcmd = new BaseCommand();
  if (bcmd->ParseFromString(sl))
  {
    printf("ParsePartialFromString ok\n");
  }
  

  printf("%d\n", bcmd->type());
  switch(bcmd->type())
  {
    case BaseCommand::LOGIN:
    {
      printf("login\n");
      printf("%s %s\n", b.MutableExtension(Login::cmd)->username().c_str(), b.MutableExtension(Login::cmd)->password().c_str());

      break;
    }
    case BaseCommand::VERSION:
    {
      printf("version\n");


      printf("%d %d\n", b.MutableExtension(Version::cmd)->versions(), b.MutableExtension(Version::cmd)->protocol());
      break;
    }
    default:
      break;
  }

  return 1;
}

example.java


import example.Commands;
import example.Commands.BaseCommand;
import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.ExtensionRegistry;
import java.io.IOException;

 
class ProtoBufExample {
        // Helper which wraps the BaseCommand around the extension command
        static  BaseCommand wrap(BaseCommand.CommandType type, GeneratedMessage.GeneratedExtension extension, Type cmd) {
                return BaseCommand.newBuilder().setType(type).setExtension(extension, cmd).build();
        }
 
        ExtensionRegistry registry;
 
        ProtoBufExample() {
                // we need to register all the extensions and tell the decoder about them
                // otherwise the extension will be ignored
                registry= ExtensionRegistry.newInstance();
                Commands.registerAllExtensions(registry);
        }
 
        BaseCommand buildVersion(int v1, int v2) {
                Commands.Version vers= Commands.Version.newBuilder().setProtocol(v1).setVersions(v2).build();
                // BaseCommand bcmd= BaseCommand.newBuilder().setType(BaseCommand.CommandType.VERSION).setExtension(Commands.Version.cmd, vers).build();
                return wrap(BaseCommand.CommandType.VERSION, Commands.Version.cmd, vers);
        }
 
        BaseCommand buildLogin(String username, String password) {
                Commands.Login l= Commands.Login.newBuilder().setUsername(username).setPassword(password).build();
                return wrap(BaseCommand.CommandType.LOGIN, Commands.Login.cmd, l);
        }
 
        BaseCommand decodeIt(byte [] ba) {
                // use the registry so extensions will be decoded
            try{
                BaseCommand b=BaseCommand.newBuilder().mergeFrom(ba, registry).build();
                return b;
            }
            catch (IOException e) {
                System.out.println("Unable to create  " +e.getMessage());
                return buildVersion(0,1);
            }

        }

 
    public static void main(String[] args) throws Exception {
        ProtoBufExample pb= new ProtoBufExample();
        BaseCommand b= pb.buildVersion(1234, 5678);
        //BaseCommand b= pb.buildLogin("user1", "test");
 
        System.out.println(b);
        System.out.println ("size: " + b.toByteArray().length);
 
        BaseCommand decoded= pb.decodeIt(b.toByteArray());
 
        System.out.println ("We got a "+ decoded.getType() +" message");
 
        // We can switch on the CommandType enum and extract the specific command type (extension) we got
        switch(decoded.getType()) {
        case VERSION:
            System.out.println (decoded.getExtension(Commands.Version.cmd));
            break;
                
        case LOGIN:
            System.out.println (decoded.getExtension(Commands.Login.cmd));
            break;
 
        default:
            System.out.println ("Don't know this type");
        }
    }
    
}

Using Protobuf


C++


$ SRC_DIR=`pwd`
$ ../protobuf-2.4.1/src/protoc -I=$SRC_DIR --cpp_out=. $SRC_DIR/addressbook.proto

$ g++ addressbook.pb.cc writeMsg.cpp -o writeMsg -I ../protobuf-2.4.1/src -L ../protobuf-2.4.1/src/.libs/ -l protobuf

$ export LD_LIBRARY_PATH=../protobuf-2.4.1/src/.libs

$ ./writeMsg address.txt

$ g++ addressbook.pb.cc readMsg.cpp -o readMsg -I ../protobuf-2.4.1/src -L ../protobuf-2.4.1/src/.libs/ -l protobuf

$ ./readMsg address.txt

Person ID: 12
  Name: me
  E-mail address: me@t.net
  Home phone #: 123533333

$ ls
addressbook.pb.cc  addressbook.proto  readMsg      writeMsg
addressbook.pb.h   address.txt        readMsg.cpp  writeMsg.cpp

Java


 ../protobuf-2.4.1/src/protoc  --java_out=../protobuf-2.4.1/java/src/main/java -I ../protobuf-2.4.1/src ../protobuf-2.4.1/src/google/protobuf/descriptor.proto

cd ../protobuf-2.4.1/java/src/main/java/com/google/protobuf
javac *
cd -

export CLASSPATH=../protobuf-2.4.1/java/src/main/java:.

javac com/example/tutorial/Addressbook.java 

javac writeMsg.java

java AddPerson

javac readMsg.java 

java ListPeople ../c++/address.txt

Person ID: 12
  Name: me
  E-mail address: me@t.net
  Home phone #: 123533333

Current Week Number

$ date +%W
42

rpmbuild with rpmrc

RPM_DIR=`pwd`/rpm
echo "%_topdir $RPM_DIR" > rpmmacros
echo "macrofiles:     /usr/lib/rpm/macros:/usr/lib/rpm/%{_target}/macros:/usr/lib/rpm/redhat/macros:/etc/rpm/macros.*:/etc/rpm/macros:/etc/rpm/%{_target}/macros:~/.rpmmacros:rpmmacros" > rpmrc

mkdir -p $RPM_DIR/{BUILD,RPMS,SOURCES,SPECS,SRPMS}

rpmbuild --rcfile rpmrc --rebuild some.source.rpm

rpmbuild --rcfile rpmrc --define 'dist .el5' -without java -without python \
 --target=x86_64 -ba rpm/SPECS/protobuf.spec
or redefine topdir as
rpmbuild --define "_topdir /home/user/rpmdir" --define 'dist .el5' \
 -without java -without python  --target=x86_64 -ba rpm/SPECS/protobuf.spec

use one thread to build for easy debugging
$ cat ~/.rpmmacros 
%_smp_mflags  -j1

RPM Spec File

Show Spec Macros

rpm --showrc
rpm --eval %{_tmppath}
rpm --eval %{_libdir}

Variables

${LINUX_VERSION}   # shell environment var
%{LINUX_VERSION}     # marco var
%define LINUX_VERSION ${LINUX_VERSION}    # ${LINUX_VERSION} not evaluated
%define LINUX_VERSION $(echo ${LINUX_VERSION}) # evaluated ${LINUX_VERSION}= 2.6.32.1

More Macros

http://www.rpm.org/wiki/PackagerDocs/Macros

TCP Shutdown and Close

http://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable

Building Kernel Modules

% sudo yum install kernel-devel

% make -C /lib/modules/$(uname -r)/build/ M=$(pwd) modules

% strip --strip-debug themoudule.ko

% make -C /lib/modules/$(uname -r)/build/ M=$(pwd) clean

Building inside kernel tree


make SUBDIRS=drivers/acpi/ modules
make SUBDIRS=drivers/acpi/ button.ko

Linux User Space i2c

http://www.google.ca/url?sa=t&rct=j&q=&esrc=s&source=web&cd=10&ved=0CGkQFjAJ&url=http%3A%2F%2Fwww.haifux.org%2Flectures%2F258%2Fgpio_spi_i2c_userspace.pdf&ei=hu8EUKyaE8TNqgHrw-CxCA&usg=AFQjCNG-QNxl7brpTBTnzO2_JckFhdlC2Q modprobe i2c-dev

CISCO Switch Commands

Show Commands

show version
show boot 
show running-config
show ip interface
show file system
show ip int brief | excl unassigned
dir
cd

Configure IP

enable
configure t
interface vlan1
ip address 192.168.11.200 255.255.255.0
no shutdown

Upgrade

Method 1, copy tar file and extract tar file

copy tftp://192.168.11.1/c2960c405-universalk9-tar.150-2.SE.tar c2960c405-universalk9-tar.150-2.SE.tar
verify /md5 flash:/c2960c405-universalk9-tar.150-2.SE.tar
config terminal
boot system flash:/c2960c405-universalk9-mz.150-2.SE/c2960c405-universalk9-mz.150-2.SE.bin

Method 2, use archive commands which works with tar archive

archive download-sw  /leave-old-sw /reload  tftp://192.168.11.1/c2960c405-universalk9-tar.150-2.SE.tar

Method 3, bin file upgrade

copy tftp://192.168.11.1/c3560c405ex-universalk9-mz.150-2.SE.bin c3560c405ex-universalk9-mz.150-2.SE.bin
config terminal
boot system flash:c3560c405ex-universalk9-mz.150-2.SE.bin

Other commands

?
copy ?
delete /force /recursive c2960c405-universalk9-mz.150-2.SE

copy system:running-config tftp://192.168.11.1/running-config

copy nvram:startup-config tftp://192.168.11.1/startup-config

copy running-config startup-config

show ip int brief | excl unassigned

vlan


config t
interface vlan303
 ip address dhcp
end

##wan
interface GigabitEthernet0/10
switchport access vlan 303
 switchport mode access
 no cdp enable
 spanning-tree portfast
 spanning-tree bpdufilter enable

##lan
interface GigabitEthernet 0/5
switchport access vlan 303
 switchport mode access

SNMP exec and extend

# cat /etc/snmp/snmpd.conf
rocommunity  public
exec .1.3.6.1.4.1.2021.51 ps /bin/ps
exec .1.3.6.1.4.1.2021.50 shelltest /bin/sh /tmp/shtest
exec .1.3.6.1.4.1.2021.52 echotest /bin/echo hello world
exec echotest11 /bin/echo hello world
extend .1.3.6.1.4.1.2021.56 shelltest1 /bin/sh /tmp/test

# snmpwalk -v 1 -c public localhost .1.3.6.1.4.1.2021.8
UCD-SNMP-MIB::extIndex.1 = INTEGER: 1
UCD-SNMP-MIB::extNames.1 = STRING: echotest11
UCD-SNMP-MIB::extCommand.1 = STRING: /bin/echo hello world
UCD-SNMP-MIB::extResult.1 = INTEGER: 0
UCD-SNMP-MIB::extOutput.1 = STRING: hello world
UCD-SNMP-MIB::extErrFix.1 = INTEGER: 0
UCD-SNMP-MIB::extErrFixCmd.1 = STRING: 


# snmpwalk -v 1 -c public localhost .1.3.6.1.4.1.2021.52
UCD-SNMP-MIB::ucdavis.52.1.1 = INTEGER: 1
UCD-SNMP-MIB::ucdavis.52.2.1 = STRING: "echotest"
UCD-SNMP-MIB::ucdavis.52.3.1 = STRING: "/bin/echo hello world"
UCD-SNMP-MIB::ucdavis.52.100.1 = INTEGER: 0
UCD-SNMP-MIB::ucdavis.52.101.1 = STRING: "hello world"
UCD-SNMP-MIB::ucdavis.52.102.1 = INTEGER: 0
UCD-SNMP-MIB::ucdavis.52.103.1 = ""


# snmpwalk -v 1 -c public localhost .1.3.6.1.4.1.2021.50
UCD-SNMP-MIB::ucdavis.50.1.1 = INTEGER: 1
UCD-SNMP-MIB::ucdavis.50.2.1 = STRING: "shelltest"
UCD-SNMP-MIB::ucdavis.50.3.1 = STRING: "/bin/sh /tmp/shtest"
UCD-SNMP-MIB::ucdavis.50.100.1 = INTEGER: 127
UCD-SNMP-MIB::ucdavis.50.101.1 = STRING: "/bin/sh: /tmp/shtest: No such file or directory"
UCD-SNMP-MIB::ucdavis.50.102.1 = INTEGER: 0
UCD-SNMP-MIB::ucdavis.50.103.1 = ""
[root@vsp-devel ~]# snmpwalk -v 1 -c public localhost .1.3.6.1.4.1.2021.50
UCD-SNMP-MIB::ucdavis.50.1.1 = INTEGER: 1
UCD-SNMP-MIB::ucdavis.50.2.1 = STRING: "shelltest"
UCD-SNMP-MIB::ucdavis.50.3.1 = STRING: "/bin/sh /tmp/shtest"
UCD-SNMP-MIB::ucdavis.50.100.1 = INTEGER: 127
UCD-SNMP-MIB::ucdavis.50.101.1 = STRING: "/bin/sh: /tmp/shtest: No such file or directory"
UCD-SNMP-MIB::ucdavis.50.102.1 = INTEGER: 0
UCD-SNMP-MIB::ucdavis.50.103.1 = ""

# snmpwalk -v 1 -c public localhost .1.3.6.1.4.1.2021.51
UCD-SNMP-MIB::ucdavis.51.1.1 = INTEGER: 1
UCD-SNMP-MIB::ucdavis.51.2.1 = STRING: "ps"
UCD-SNMP-MIB::ucdavis.51.3.1 = STRING: "/bin/ps"
UCD-SNMP-MIB::ucdavis.51.100.1 = INTEGER: 0
UCD-SNMP-MIB::ucdavis.51.101.1 = STRING: "  PID TTY          TIME CMD"
UCD-SNMP-MIB::ucdavis.51.101.2 = STRING: "    1 ?        00:00:01 init"
UCD-SNMP-MIB::ucdavis.51.101.3 = STRING: "    2 ?        00:00:00 migration/0"
UCD-SNMP-MIB::ucdavis.51.101.4 = STRING: "    3 ?        00:00:00 ksoftirqd/0"
UCD-SNMP-MIB::ucdavis.51.101.5 = STRING: "    4 ?        00:00:00 watchdog/0"
UCD-SNMP-MIB::ucdavis.51.101.6 = STRING: "    5 ?        00:00:00 migration/1"
UCD-SNMP-MIB::ucdavis.51.101.7 = STRING: "    6 ?        00:02:33 ksoftirqd/1"
UCD-SNMP-MIB::ucdavis.51.101.8 = STRING: "    7 ?        00:00:00 watchdog/1"
UCD-SNMP-MIB::ucdavis.51.101.9 = STRING: "    8 ?        00:00:00 events/0"
UCD-SNMP-MIB::ucdavis.51.101.10 = STRING: "    9 ?        00:00:00 events/1"
UCD-SNMP-MIB::ucdavis.51.101.11 = STRING: "   10 ?        00:00:00 khelper"
UCD-SNMP-MIB::ucdavis.51.101.12 = STRING: "   11 ?        00:00:00 kthread"
UCD-SNMP-MIB::ucdavis.51.101.13 = STRING: "   15 ?        00:00:04 kblockd/0"
UCD-SNMP-MIB::ucdavis.51.101.14 = STRING: "   16 ?        00:00:00 kblockd/1"
UCD-SNMP-MIB::ucdavis.51.101.15 = STRING: "   17 ?        00:00:00 kacpid"
UCD-SNMP-MIB::ucdavis.51.101.16 = STRING: "  131 ?        00:00:00 cqueue/0"
UCD-SNMP-MIB::ucdavis.51.101.17 = STRING: "  132 ?        00:00:00 cqueue/1"
UCD-SNMP-MIB::ucdavis.51.101.18 = STRING: "  135 ?        00:00:00 khubd"
UCD-SNMP-MIB::ucdavis.51.101.19 = STRING: "  137 ?        00:00:00 kseriod"
UCD-SNMP-MIB::ucdavis.51.101.20 = STRING: "  205 ?        00:00:00 khungtaskd"
UCD-SNMP-MIB::ucdavis.51.101.21 = STRING: "  208 ?        00:00:07 kswapd0"
UCD-SNMP-MIB::ucdavis.51.101.22 = STRING: "  209 ?        00:00:00 aio/0"
UCD-SNMP-MIB::ucdavis.51.101.23 = STRING: "  210 ?        00:00:00 aio/1"
UCD-SNMP-MIB::ucdavis.51.101.24 = STRING: "  370 ?        00:00:00 kpsmoused"
UCD-SNMP-MIB::ucdavis.51.101.25 = STRING: "  402 ?        00:00:00 scsi_eh_0"
UCD-SNMP-MIB::ucdavis.51.101.26 = STRING: "  403 ?        00:01:17 usb-storage"
UCD-SNMP-MIB::ucdavis.51.101.27 = STRING: "  408 ?        00:00:00 ata/0"
UCD-SNMP-MIB::ucdavis.51.101.28 = STRING: "  409 ?        00:00:00 ata/1"
UCD-SNMP-MIB::ucdavis.51.101.29 = STRING: "  410 ?        00:00:00 ata_aux"
UCD-SNMP-MIB::ucdavis.51.101.30 = STRING: "  417 ?        00:00:00 kstriped"
UCD-SNMP-MIB::ucdavis.51.101.31 = STRING: "  430 ?        00:00:00 ksnapd"
UCD-SNMP-MIB::ucdavis.51.101.32 = STRING: "  447 ? "
UCD-SNMP-MIB::ucdavis.51.102.1 = INTEGER: 0
UCD-SNMP-MIB::ucdavis.51.103.1 = ""

YUM Remove Orphaned Packages

Find Orphaned Packages

package-cleanup --orphans
Then remove the old fc-xx packages that no longer supported with "yum remove".

Fedora 17 Nouveau Driver

X does not load with default Nouveau driver option. Add the following to the kernel option to make it work
nouveau.noaccel=1
Alternatively create /etc/modprobe.d/noaccel.conf with
options nouveau noaccel=1

rpmbuild anaconda

$ echo "%_topdir     /home/$USER/anaconda/rpm" > ~/.rpmmacros

$ cd ~/anaconda
$ mkdir -p rpm/{BUILD,RPMS,SOURCES,SPECS,SRPMS}

$ rpm -i anaconda-11.1.2.113-1.el5.centos.2.src.rpm   #extract source

$ cd rpm/SPECS

$ rpmbuild -ba anaconda.spec

Building loader

$ cd rpm/BUILD/anaconda-11.1.2.209/loader2
$ make loader

Repacking Centos Stage2 Image

Extracting

/usr/sbin/unsquashfs -dest centos-stage2 stage2.img


Repacking

# cd centos-stage2
# tar cf - * .buildstamp | (cd ../centos-stage2-new; tar xfp -)

// make change in centos-stage2-new

# cd centos-stage2-new
# mksquashfs . ../stage2.img.new -all-root -no-fragments -noappend


Using rpm2cpio to extract rpms

rpm2cpio some.rpm | cpio -idmv

PCI (Linux)

Identity

Each device is identified by a
  • domain (0000 each domain can have 256 buses)
  • bus number (00)
  • device number (00)
  • function (0)

# update-pciids      #update pci ids

# lspci
 00:00.0 Host bridge: Intel ...

# lspci -tv
-[0000:00]-+-00.0  Intel Corporation ...
           +-01.0-[0000:01-06]----00.0  Intel Corporation 82574L Gigabit Network Connection

Address Spaces

  1. Configuration
  2. I/O
  3. Memory

SYSFS

The address spaces (config, io, memory) can be seen from the sysfs tree.

config

# lspci -s 00:1f.3 -x
00:1f.3 SMBus: Intel Corporation 6 Series/C200 Series Chipset Family SMBus Controller (rev 04)
00: 86 80 22 1c 03 00 80 02 04 00 05 0c 00 00 00 00
10: 04 60 52 c2 00 00 00 00 00 00 00 00 00 00 00 00
20: 41 40 00 00 00 00 00 00 00 00 00 00 86 80 22 1c
30: 00 00 00 00 00 00 00 00 00 00 00 00 0a 03 00 00

# od -x /sys/devices/pci0000:00/0000:00:1f.3/config
0000000 8086 1c22 0003 0280 0004 0c05 0000 0000
0000020 6004 c252 0000 0000 0000 0000 0000 0000
0000040 4041 0000 0000 0000 0000 0000 8086 1c22
0000060 0000 0000 0000 0000 0000 0000 030a 0000
0000100 0001 0000 0000 0000 0000 0000 0000 0000
0000120 0000 0000 0000 0000 0000 0000 0000 0000
0000140 0403 0004 0000 0808 0000 0000 0000 0000
0000160 0000 0000 0000 0000 0000 0000 0000 0000
0000200 0004 0000 0000 0000 0000 0000 0000 0000
0000220 0000 0000 0000 0000 0000 0000 0000 0000
*
0000360 0000 0000 0000 0000 0f87 0806 0000 0000

I/O and Memory

These can be mmap'ed

# ll /sys/devices/pci0000:00/0000:00:1f.3/resource*
-r--r--r-- 1 root root 4096 Jul  5 17:46 /sys/devices/pci0000:00/0000:00:1f.3/resource
-rw------- 1 root root  256 Jul  5 17:46 /sys/devices/pci0000:00/0000:00:1f.3/resource0
-rw------- 1 root root   32 Jul  5 17:46 /sys/devices/pci0000:00/0000:00:1f.3/resource4

# lspci -v
00:1f.3 SMBus: Intel Corporation 6 Series/C200 Series Chipset Family SMBus Controller (rev 04)
        Subsystem: Intel Corporation 6 Series/C200 Series Chipset Family SMBus Controller
        Flags: medium devsel, IRQ 201
        Memory at c2526000 (64-bit, non-prefetchable) [size=256]
        I/O ports at 4040 [size=32]

resource0 (BAR0) is the memory
resource4 (BAR4) is IO ports

Other Useful

Below is how you can find the driver used for the device

# lspci |grep Ether
00:19.0 Ethernet controller: Intel Corporation 82579LM 

# lspci -s 00:19.0 -n
00:19.0 0200: 8086:1502 (rev 04)

# grep 1502 /lib/modules/2.*/modules.pcimap
e1000e               0x00008086 0x00001502 0xffffffff 0xffffffff 0x00000000 0x00000000 0x0

Java Basics

Primitive Types

byte
char - 16 bit
short
int
long - 64 bit
boolean
float
double

Variables

  • variable of primitive types holds value.
  • variable of non-primitive types holds reference.

Variable Storage

  • Static - static class variables
  • Local  - primitives
  • Dynamic - non-primitives

Parameters

  • All the parameters are pass-by-value (since the variables can only be value or reference; for reference it is a copy of the reference). 
  • There is no direct way change content of a primitive type with parameter (can wrap with array or object).

Class

Accessibility

public
private
protected - subclass and class from the same package.
package - member without any leading keyword get default package access.

  • no C++ const method
  • no ";" after class {}

Inheritance

  • no C++ multiple inheritance
  • Object is default base class if no base class is specified. Which is the root base class for all classes.
  • super is used to initialize superclass.

import Person;
public class Student extends Person
{
   private String major;
   public Student(String name, String major)
   {
      super(name);
      this.major=major;
   }
} 

Static and Dynamic Binding

  • virtual by default

 void a();  //C++==>  virtual void a();


Abstract Methods


abstract a();  //C++==> virtual void a()=0;

Call Superclass Version


super.a();     //C++==> baseName::a();

Final Methods

  • Cannot be overriden in a subclass

final void a();
 

Exceptions

  • Java exception class must be a subclass of the java.lang.Exception class (which is a subclass of java.lang.Throwable).
  • C++ exception can be of any class.

Features of C++ does not exist in Java

  • Preprocessor
  • Enumeration Types
  • Templates
  • Operator Overloading
  • Named types (typedef)
  • Structs and unions
  • const class function member.

Python Basics

Debugging

http://docs.python.org/library/pdb.html
python -m pdb my.py

# launch pdb after a crash.
import pdb; pdb.set_trace()   

# compile without executing it
python -m py_compile test.py 

Lib Path

export PYTHONPATH=/home/python
$ python
Python 2.4.3 (#1, May 24 2008, 13:47:28) 
[GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/python', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/Numeric', '/usr/lib/python2.4/site-packages/gtk-2.0']

Useful

help(int)
dir(int)
locals()
globals()

Variables

everything in python is an object. 
All python variables hold value of references to objects.
parameter passing is by value.
String, numbers, tuples are immutable. 

Integers, floats, complex numbers, booleans
x = 5
y = 6
print `x`;
print "x is %i y is %i" % (x, y)
 

Lists

a=[1,4,5,6]
b=[1,"two",3,["a","b"],4]

Tuples

Same as lists but not changeable
a=(1,2)
b=(1,"two",3,["a","b"],4)

Dictionaries

a={1:"one", 2:"two"}
a["first"]="one";
list(a.keys())
a.get(1, "not availabe)

Sets

unorder collection of objects.
>>> x=set([1,2,3,2,4,1])
>>> x
set([1, 2, 3, 4])
>>> 1 in x
True
>>> 6 in x
False

Conditionals

if x < 10:
   y = 1
elif x > 12:
   y = 2
else:
   y = 3

Loops

For
for x in [1,2,3,4,5]:
  print x;
While
x=5
while x < 10:
  print x
  x=x+1

Functions

def func(x, y, z):
   print (x, y, z)
   print x, y, z
func(1,2,3)
mult=lambda x,y: x * y   # return is implicit
map( lambda x: x*x, [1,2,3,4])
filter(lambda x: x > 3, [ 1,2,3,4,5,6])

Class

class X:
  "Sample class"
  x=5
  def setVal(self,val):
    self.x=val

External Commands

os.system
import os
res=os.system("ls myfile");
if res>>8 != 0:
  print "err"
commands
import commands
>>> res, output = commands.getstatusoutput('ls /bin/ls')
>>> res
0
>>> output
'/bin/ls'
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x. 1 root root 105112 Feb  8  2011 /bin/ls'

Perl Basics

Debugging

 -w option
Debugger
perl -w -d my.pl  # with perl
perl -w -d -e "1;"    # no code

Variables

Perl has 3 kinds of variables:
  • scalar
  • array
  • hash 
Parameters can only be scalar. To pass other kind, it needs to be converted to a scalar (using reference).
scalar
$a=5; 
local $b='hello';
Array
my @num=(1,2,3);
my @str=("hello", "one");
my @mixed=("hello",1,2);
print $mixed[1];

@colors = ("red","green","blue");
($a, @somecolors) = @colors; # $a is first item; @somecolors are rest of @colors
(@somecolors, $a) = @colors; # @somecolors are @colors; $a is undefined
Hash
%fruit = (
       one => "apple",
       two => "orange",
       three => "peach"
       );

@key = keys %fruit;
@value = values %fruit;
print "$fruit{one} $key[1] $value[1]\n";

#hash of hashes
%HoH = (
  t1 => { a1 => "a1",
          a2 => "a2",},
  t2 => { b1 => "b1",
          b2 => "b2",},
);
print "$HoH{t1}{a2}\n";

Complex Data Type using Reference

# reference
$multiple = {
  m1 => { 
           onee => "app",
                  twoo => "ppa",
         },
         m2 => {
           test => "t",
    test2 => "y",
                },

};


print "$multiple->{m1}{onee} \n";

Conditionals

# if
if ( condition ){
  ...
}
elsif (condition ) {
  ...
}
else{
  ...
}

# unless
unless ( condition )
{
   ...
}

Loop

While
while (condition) { ... }
until (condition) { ... }
for
for ($i = 0; $i < 10; $i++)
{
   ...
}

for my $i ('a','b','c'){
  print $i;
}
foreach
foreach my $file (@mdfiles) 
{
   print "$file";
}

foreach (@array) {
   print "$_\n";
}

print $list[$_] foreach 0 .. $max;

foreach my $key (keys %hash) {
    print "The value of $key is $hash{$key}\n";
}

Operators

Numbers
 ==, !=, <, >, <=, >= 
Strings
 eq, ne, le, ge, lt, gt

Regular Expression

if (/tst/) { ... }         # true if $_ contains "tst"
if ($a =~ /hello/) { ... } # true if $a contains "hello"

s/a/b/;                    # replaces a with b in $_
$a =~ s/a/b/;              # replaces a with b in $a

External Commands

#1
$res = system("ls");

#2
my $exam=`mdadm --examine /dev/$dev 2>&1`; 

if ($? != 0){
   print "error\n";
}

Functions

sub setError($)
{
    $errorCode |= shift;
    return 1;
}
 

Bash Programming Basics

Debugging

Start up the shell with the -x option, which will run the entire script in debug mode. Traces of each command plus its arguments are printed to standard output after the commands have been expanded but before they are executed.
#!/bin/bash -x        #on first line

Variable

a=5
export b='whatever'
c="$a $b"
d='$a $e'                                    # no substitution
local e=56

Array

list=(/tmp/m*)
echo ${#list[@]}
echo ${list[0]} 
echo ${list[@]}
echo ${list[*]} # same as @

Conditionals

Empty or unset variable
if [[ ${b:-z} == z ]]; then 
    echo "variable is empty or unset"; 
fi
String
if [ "a" = "b" ]; then
  echo yes;
else                                         #elif
  echo no
fi
multiple condition
if [ "a" = "b" -a "c" == "c" ]; then       # string = or ==
  echo "and condition true";
else                                         #elif
  echo no
fi

if [ "a" = "b" -o "c" == "c" ]; then       # string = or ==
  echo "or condition true";
else                                         #elif
  echo no
fi

if [[ $a == "b" && $b == "c" ]]; then
   echo yes;
fi

[[ -f $NATION_FILE ]] || fail "No nation file";
Numbers
if [ 5 -eq $? ]; then                         # numbers
  echo yes
fi
commands
if grep a * >/dev/null; then 
  echo yes; 
fi

Loop

For loop
for each in $(ls); do
  echo $each
done
While loop
COUNTER=0
while [  $COUNTER -lt 10 ]; do
    echo The counter is $COUNTER
    COUNTER=$((COUNTER+1)) 
done
Util
COUNTER=20
until [  $COUNTER -lt 10 ]; do
     echo COUNTER $COUNTER
     let COUNTER-=1
done

Read Each Line in a Variable

files=$(ls -1)
echo "$files"      # one line
echo $files | while read -r line; do echo $line; done    #one line
echo "$files" | while read -r line; do echo $line; done  # per line
echo "$files"|xargs  echo      #one line
echo "$files"|xargs -L1 echo   # per line

Functions

myecho()
{
  echo $*  
  echo $@
}

func_parm()
{
  [ -z $1 ] || echo parm missing && exit 1
  echo parm
}

Signal Handling

handle_int()
{
  echo "Control C"
}

trap handle_int SIGINT 

Manipulating Strings

http://tldp.org/LDP/abs/html/string-manipulation.html
${#String}
${string:position}
${string:position:length}
${string#substring}
${string##substring}

Redirection

   1>filename
      # Redirect stdout to file "filename."
   1>>filename
      # Redirect and append stdout to file "filename."
   2>filename
      # Redirect stderr to file "filename."
   2>>filename
      # Redirect and append stderr to file "filename."
   &>filename
      # Redirect both stdout and stderr to file "filename."
      # This operator is now functional, as of Bash 4, final release.

   M>N
     # "M" is a file descriptor, which defaults to 1, if not explicitly set.
     # "N" is a filename.
     # File descriptor "M" is redirect to file "N."
   M>&N
     # "M" is a file descriptor, which defaults to 1, if not set.
     # "N" is another file descriptor.

Operators

Numbers
arg1 OP arg2
       OP  is one of -eq, -ne, -lt, -le, -gt, or -ge.  These arithmetic binary operators return true if arg1 is equal
       to, not equal to, less than, less than or equal to, greater than, or greater than or equal  to  arg2,  respec‐
       tively.  Arg1 and arg2 may be positive or negative integers.  
String
string
-n string
       True if the length of string is non-zero.

string1 == string2
string1 = string2
       True if the strings are equal.  = should be used with the test command for POSIX conformance.

string1 != string2
       True if the strings are not equal.

string1 < string2
       True if string1 sorts before string2 lexicographically.

string1 > string2
       True if string1 sorts after string2 lexicographically.