eTechtips

Tech Tips and Insights

Category: Programming

  • C: Check if string is a number

    I was recently testing some basic input and wrote this code to test if the input was a number or not.

    #include 
    
    int main()
    {
      char name[10];
    
      scanf("%s",&name);
      if (checkifNumber(name))
      {
         printf("Is a numbern"); 
      }
      else
      {
         printf("Invalid numbern");
      }
    }
    
    int checkifNumber(char *inp)
    {
      int i=0;
      int isanumber = 1;
    
      while(inp[i] != '' && i < 10)
      {
        if (inp[i] >= '0' && inp[i] <= '9')
        {
        }
        else
        {
          isanumber =0;
        }
        i++;
      }
      return isanumber;
    }
    

    One thing that could be improved is to potentially use a global variable to define the length of the
    input string as it is used in two different places in the program and could potentially lead to an
    array overrun/underrun.

    0 Comments
  • Dos: Adding commands to the PATH

    When you install a new piece of software that does not add itself to the Windows PATH variable, you may find your self
    needing it to be run from a command prompt. You could type the full command path each time you run the executable, but
    it may be easier to add the directory to the PATH variable so that it is always available.

    To add it for the current command prompt:

    set PATH=%PATH%;"C:Program FilesSometool"

    This will add the variable to the current command prompt environment but will go away once you close the window and will not
    be available to other prompts unless you type it in again.

    To add it to the Windows Environment, you can use the My Computer->Properties menu to select the “Advanced System Settings”
    in Windows 7 to then select the “Environment Variables…”. Now the choice you have is to add it to the System variables or
    the User variables for.

    If you choose the System varables you will be adding it to the system as a whole and any other user who logs in will have
    the updated path. If you add it to the User variables, then it is only available to your user.

    Whichever you choose, select the Path entry and click the “Edit…” button. This will pop up a dialog that will let
    you add to the “Variable Value” entry. Now you will need to decide whether you want your new path at the beginning, end,
    or somewhere in the middle. You might add it to the beginning if it is being used to override an existing command. You
    may add to the end if there is no conflict with other installs. And finally, you may need to choose the middle if there
    are some commands you need to override but others that need to be left alone.

    Entries are separated by the semi-colon “;” character in DOS.

    0 Comments
  • Perl: Format date strings

    The other day I had a requirement to fill in a date value while creating an entity in ClearQuest. The field that was required was a date and was formatted as “mm/dd/yyyy hh:MM::SS AM|PM”. I used the localtime function to return the date and used sprintf to format the date to the proper output.
    The reason I used sprintf was that for hours, months and days less 10 the output was 1 digit instead of two and the input was not allowed. The %02d states that the digits used will be a minumum of 2 in this case.

    Here is the sample program I wrote to test the expected output:

     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
    
    # formatted just by concatenating output
    my $datestring = $mon . "/" . $mday . "/" . $year . "  " . $hour . ":" . $min.
    ":" . $sec  ;
    
    # formatted using sprintf to ensure proper digit counts are output
    my $datestring2 = sprintf("%02d/%02d/%04d %d:%02d:%02d %s",$mon,$mday,1900 +$yea
    r,$hour,$min,$sec, $hour >= 12? "PM" : "AM");
    
     print $datestring;
      print $datestring2;
    
    
    0 Comments
  • XML: Characters that require replacement

    I was generating some html based e-mails and due to some changes I made in the text, my mail stopped being sent. I found that it was not liking some of the characters that were being placed in my generated emails. I tried some of the standard replacemnt methods, but found that the XML file was the issue. The Greater than(>) and less than (<) and the Amersand(&) and the apostrophe(') and the quote(") all have special meaning to XML and can cause these issues. Once I replaced the following characters in my email variable, my e-mails began to flow again. Here is a table of the characters and their XML representations that can be used for replacement:

    Name Character XML replacement
    Ampersand & &
    Apostrophe ' &apos;
    Greater Than >r &gt;
    Less than < &lt;
    Quote " &quot;

    This is by no means the complete list of replacements. This is only that characters that were needed by the calls to Java Mail that my program was using.

    0 Comments
  • JAVA: XMLGregorianCalendar Dates

    I was updating some plugins for a project and came to a query for an e-mail program I was writing, I had to send out recently introduced defects to their respective owners and insure that they would only get the defects from the a given offset. It turned out that my API had a XMLGregorianCalendar argument. So I went out to look for a way to offset the date object so I could retrieve the correct information.

    I used the following to convert my date:

    package com.etechtips;
    
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    
    import javax.xml.datatype.DatatypeConfigurationException;
    import javax.xml.datatype.DatatypeFactory;
    import javax.xml.datatype.XMLGregorianCalendar;
    
    public class UpdateDate {
    
    	public static void main(String[] args) {
    		XMLGregorianCalendar xgcstart;
    		GregorianCalendar gc;
    		int daycount = 0;
    		if (args.length != 1)
    		{
    			System.out.println("Need to specify offset");
    			System.exit(1);
    		}
    		
    		daycount = Integer.parseInt(args[0]);
    		
    		// This will get the current date based on System time of an object
    		gc = new GregorianCalendar();
    		System.out.println("CURRENT:" + gc.toString());
    
    		// This will offset the date by daycount days
    		gc.add(Calendar.DATE, daycount);
    		System.out.println("OFFSET: "+ gc.toString());
    		
    		try
    		{
    			// Now the XMLGregorianCalendar object has an 
                            instance that is based on the time set in the gc object
    			xgcstart = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
    		}
    		catch(DatatypeConfigurationException dce)
    		{
    			dce.printStackTrace();
    			System.exit(1);
    		}
    		
    		// Code omitted 	
    	}
    }
    

    Output:

    CURRENT:java.util.GregorianCalendar[time=1321793315934,areFieldsSet=true,areAllFieldsSet=true,
    lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Chicago",offset=-21600000,
    dstSavings=3600000,useDaylight=true,transitions=235,
    lastRule=java.util.SimpleTimeZone[id=America/Chicago,offset=-21600000,dstSavings=3600000,
    useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,
    startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,
    endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2011,MONTH=10,
    WEEK_OF_YEAR=48,WEEK_OF_MONTH=4,DAY_OF_MONTH=20,DAY_OF_YEAR=324,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=3,
    AM_PM=0,HOUR=6,HOUR_OF_DAY=6,MINUTE=48,SECOND=35,MILLISECOND=934,ZONE_OFFSET=-21600000,
    DST_OFFSET=0]
    OFFSET: java.util.GregorianCalendar[time=1321706915934,areFieldsSet=true,areAllFieldsSet=true,
    lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Chicago",offset=-21600000,
    dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/Chicago,
    offset=-21600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,
    startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,
    endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,
    YEAR=2011,MONTH=10,WEEK_OF_YEAR=47,WEEK_OF_MONTH=3,DAY_OF_MONTH=19,DAY_OF_YEAR=323,
    DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=6,HOUR_OF_DAY=6,MINUTE=48,SECOND=35,
    MILLISECOND=934,ZONE_OFFSET=-21600000,DST_OFFSET=0]
    

    The printouts above show the current date and the new date based on the offset. I made the day of the month bold in the printouts to show what the offset has updated the date. You could put a much larger offset than 1 and Calendar object will take care of updating the day of week, week of year and more. You will not need to deal with checking for leap year or dealing with updating all the month and years, this is all taken care of for you.

    0 Comments
  • DOS: Check for empty environment variable

    I was writing a batch file the other day and needed to change the argumets to a command based on if the user had specified his password on the command line.

    SET PASS=somepassword
    : or
    :SET PASS=
    if x%PASS%= X (
      SET PASSARG=--password somepassword
    ) else
    (
      SET PASSARG=
    )
    
    commandtorun %PASSARG%
    

    Now if the user comments out his password, the script will make the PASSARG environment variable be empty or if they set a password the passarg variable will be filled in.

    0 Comments
  • Java: Command line argument processing

    In each language that I have learned I have found it useful to know how to process command line arguments and here is a simple framework that I use for Java. I usually wrap the java command line in a bat or shell file to make it easier to run so that the user does not have to worry about classpath or path issues.

    The following is the basic code to handle the command line arguments.

    class CmdArgs
    {
    
      public static void main(String[] args)
      {
          int argsize = args.length;
          String curarg;
    
          if (argsize > 0 )
          {
           
          }
          
          for(int i = 0; i < argsize; i++)
          {
              if (args[i].equals("--host"))
              {
                 i++;
                 host = args[i];
               }
              else if (args[i].equals("--debug"))
              {
                   debug = 1;
              }
              else
              {
                  System.out.println("Unknown option: " + args[i]);
                  System.exit(1);
              }
           }
    
       }
    }
    

    The bat file for Dos/Windows might look like this:

    @echo off
    
    java -cp c:javabin;somejar.jar  com.etechtips.CmdArgs %*
    

    The shell based file might look like:

    java -cp /home/ecdown/javabin:somejar.jar com.etechtips.CmdArgs $*
    
    0 Comments
  • Linux:Script to use find to search contents of files

    I use find and grep quite a bit. I found that I was regularly searching for strings in file and was typing commands like:

    find . -exec grep "somestring" {} ; --print
    

    This find command will search from the current directory and for each file will run grep on it and if it finds a matching string, it will print the string and then the filename. So I took this and moved it into a script.

    #!/bin/sh
    
    if [ $# -lt 1 ]; then
      echo 1>&2 Usage: $0 ""
      exit 127
    fi
    icase=
    search=
    
    while [ $# -ge 1 ]; do
      case $1 in
         -i) icase=$1;;
          *) search=$1 ;;
      esac
      shift
    done
    
    find . -type f -print0 | xargs -0 grep $icase $search
    

    This allows me to run a command such as

    ffind -i Super
    

    This command will search all file names starting from the current directory and recurse directories and the “-i” will tell it to ignore case.

    0 Comments
  • CSS: Background properties

    These are the individual background properties in CSS.

    background-color
    background-image
    background-repeat
    background-attachement
    background-position
    

    The background-color property specifies the color of the element. This can be useful to specify if someone has turned images off and you want a non-default view of your content. You can use a hex value (#RRGGBB), a shortcut hex value (#RGB) or a named color (red, green,blue).

    background-color: #fffffff;
    

    The background-image specifies an image to place in the background of an element. Remember that the image should be supported by as many browsers as possible. This means using jpeg, pngs or gifs, not tifs or proprietary image formats.

    background-image: url(images/someimage.gif)
    

    The background-repeat property specifies how an image should display within an element. You can have it repeat across (repeat-x), repeat downwards (repeat-y) or not repeat (no-repeat).

    background-repeat: repeat-x;
    

    The background-attachmemnt attribute is used to specify if an image should scroll (scroll) with the page, be fixed (fixed) to the page or inherit position from a parent element (inherit).

    background-attachment: fixed;
    

    The background-position attribute is used to specify the starting position of an image. This can be useful if you are using a sprite to speed up loading times. The background-position attribute can take a Xpx Ypx argument, an X% Y% argument, named arguments(left top, right bottom,…) or inherit from the parent.

    background-position: 50% 50%;
    

    Here is an example of the use of these:

     body {
       background-color: #ffffff;
       background-image: url(images/someimage.gif);
       background-repeat: no-repeat;
       background-attachment: fixed ;
       background-position: left top ;
    }
    

    You can also use a short cut method to the background property.

     .imagebox {
      background: #ffffff url(images/someimage.gif) no-repeat fixed right top;
    }
    
    0 Comments
  • CSS: Correct order to style links

    This is the correct order to place the styles in your Cascading Style Sheet(CSS) markup to style links.
    The order does matter as out of order markup can lead to lost properties.

    a:link {}
    a:visited {}
    a:focus {}
    a:hover {}
    a:active {}
    
    0 Comments