Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Wednesday, March 13, 2013

Making ant targets driven by a property

The ant apache manual clearly defines on the the use of the "if" property when there's a need to have certain ant targets run only for some criteria.

 "A target also has the ability to perform its execution if (or unless) a property has been set. This allows, for example, better control on the building process depending on the state of the system (java version, OS, command-line property defines, etc.). To make a target sense this property, you should add the if (or unless) attribute with the name of the property that the target should react to. Note: In the most simple case Ant will only check whether the property has been set, the value doesn't matter, but using property expansions you can build more complex conditions. See the properties page for more details. For example:


Expanding on this need, here's how you pass the property on the command line so its picked up by the build script
$ant clean build -Dmodule-A-present=anyvalue

Ref: http://ant.apache.org/manual/targets.html

Tuesday, November 1, 2011

Recently Analyzed Table List

Two useful queries to get a list of recently analyzed tables. Can be used to check when the tables were last analyzed. Normally oracle should analyze tables on its own.
SELECT owner,
       SUM (DECODE (NVL (num_rows, 9999999), 9999999, 0, 1)) analyzed,
       SUM (DECODE (NVL (num_rows, 9999999), 9999999, 1, 0)) not_analyzed,
       COUNT (table_name) total
  FROM all_tables
 WHERE owner NOT IN ('SYS', 'SYSTEM')
GROUP BY owner;
SELECT table_name,
       TO_CHAR (last_analyzed, 'MM/DD/YYYY HH24:MI:SS') last_analyzed
  FROM user_tab_columns
 WHERE     last_analyzed IS NOT NULL
       AND column_id = 1
       AND (SYSDATE - last_analyzed) < 30
ORDER BY 2;

Tuesday, October 18, 2011

Time difference

Query to get the time different between 2 date columns
select floor(((end_time - start_time)*24*60*60)/3600)
       || ' HOURS ' ||
       floor((((end_time - start_time)*24*60*60) -
       floor(((end_time - start_time)*24*60*60)/3600)*3600)/60)
       || ' MINUTES ' ||
       round((((end_time - start_time)*24*60*60) -
       floor(((end_time - start_time)*24*60*60)/3600)*3600 -
       (floor((((end_time - start_time)*24*60*60) -
       floor(((end_time - start_time)*24*60*60)/3600)*3600)/60)*60)))
       || ' SECS ' time_difference
from sub_email_jobs;

Tuesday, October 11, 2011

Excel Removing or adding hyperlinks

Useful code to remove and add hyperlinks in Excel using VB
Public Sub Convert_To_Hyperlinks()
    Dim Cell As Range
    For Each Cell In Intersect(Selection, ActiveSheet.UsedRange)
        If Cell <> "" Then
            ActiveSheet.Hyperlinks.Add Cell, Cell.Value
        End If
    Next
End Sub
Sub RemoveHyperlinks()

'Remove all hyperlinks from the active sheet
ActiveSheet.Hyperlinks.Delete

End Sub

Wednesday, September 7, 2011

Query to get a list of tables without any indexes

SELECT table_name
  FROM (SELECT table_name FROM user_tables
        MINUS
        SELECT table_name FROM user_indexes) orasnap_noindex
 WHERE table_name LIKE 'HSO%'
ORDER BY table_name

Sunday, August 7, 2011

Updating a table based on rows from another table

Example One:
UPDATE a
   SET data =
           (SELECT data
              FROM b
             WHERE id1 = a.id1 AND id2 = a.id2)
 WHERE EXISTS
           (SELECT 1
              FROM b
             WHERE id1 = a.id1 AND id2 = a.id2);
Example two, can be used for multiple columns
UPDATE (SELECT a.data a_data, b.data b_data
          FROM a, b
         WHERE a.id1 = b.id1 AND a.id2 = b.id2)
   SET a_data = b_data;

Queries to delete duplicates in a table

Three useful queries that I use to delete duplicate rows from tables
DELETE FROM customers
 WHERE id IN (SELECT id
                FROM (SELECT id,
                             lastname,
                             firstname,
                             RANK ()
                             OVER (PARTITION BY lastname, firstname
                                   ORDER BY id)
                                 AS seqnumber
                        FROM customers)
               WHERE seqnumber > 1);
DELETE FROM table_name
 WHERE ROWID NOT IN 
 (SELECT MAX (ROWID) 
    FROM TABLE 
    GROUP BY duplicate_values_field_name);
SELECT *
  FROM moon.sub_globals
 WHERE ROWID IN (SELECT ROWID
                   FROM (SELECT ROWID,
                                subscriber_id,
                                sub_member_id,
                                RANK ()
                                OVER (
                                    PARTITION BY subscriber_id, sub_member_id
                                    ORDER BY ROWID)
                                    AS seqnumber
                           FROM moon.sub_globals) a
                  WHERE seqnumber > 1)

Monday, June 29, 2009

A rule of thumb when writing comments in code


When you're writing code, ask yourself if someone else could come in behind you and understand it. If not, refactor the code and/or add comments to explain what you're doing.

Protected vs. Private methods in Java

Unless you have a specific reason to make the method private - like you expressly want to prevent subclasses from accessing the method - methods should be protected. This way we can subclass this tag.

if/else vs. switch

When writing code that branches on enum values, instead of if/else blocks, use the switch statement like so:

switch (selectedTab) {
case (Tab.SITES):
//do something for sites
case (Tab.CATEGORY):
//do something for category
case (Tab.DEMOGRAPHIC):
//do something for demographics
case (Tab.ALL_SITES):
//do something for all sites
}


Lengthy and nested methods: Methods should small, atomic and easy to read. Break it up like so:

switch (selectedTab) {
case (Tab.SITES):
renderSitesTab();
case (Tab.CATEGORY):
renderCategoryTab();
case (Tab.DEMOGRAPHIC):
renderDemographicsTab();
case (Tab.ALL_SITES):
renderAllSites();
}

Comparison in Enums

Tip on Enums

Instead of using id to do equality comparisons for enums, use the enum itself.

Example: Instead of
if (selectedTab.getId() == Tab.SITES.getId()) {
use:
if (selectedTab.equals(Tab.SITES)) {

StringBuilder vs. StringBuffer

A tip on StringBuilder vs. StringBuffer

  • We should be using StringBuilder over StringBuffer. It’s a drop-in replacement, all the method names and arguments are the same.

  • StringBuilder is not synchronized and therefore doesn’t require object locks everytime a method is called. The only time we’d use StringBuffer is when it’s a member variable with a possibility of multiple threads writing to it.

Thursday, February 12, 2009

Check the version of applications running on Linux

OS version: uname -a cat /etc/redhat-release Apache version: httpd -v /usr/local/apache/bin/httpd -version Jrun version For JRun 3.0, look at logs /opt/jrun/bin/jrun -version Perl /usr/sbin/perl -version (-v works too) Sendmail /usr/lib/sendmail -d0.1 -bt cat /proc/version

Monday, December 29, 2008

Problem with date format in JDBC session

The other day I came across this issue and spent some time figuring out what was going on. Hope it can help someone.

Issue:
Say there’s a stored procedure in Oracle named test_date which uses a variable of type DATE. The variable is not returned to java but simply used elsewhere in the procedure.
If I execute this procedure in oracle and check the date format, I see it’s using the format dd-mon-yyyy

If I execute this procedure over jdbc, the format I see is mm-dd-yyyy

This makes me believe that the date format used throughout the session is defined by the client (oracle vs. jdbc).

Fix:
Simple way to fix this is to alter the session at runtime and explicitly define the format used throughout the session
alter session set nls_date_format=''DD-MON-YYYY''

Friday, December 5, 2008

Good coding practices I use



  1. Write flexible code that can be changed and extended, changes in underlying technologies shouldn't ripple through the whole system

  2. Code should be maintainability – long shelf life

  3. Layers should not be tightly coupled. Each layer needs to be independent from the other. Use interfaces, dependency injection etc

  4. Indent all files using spaces (Indent once = 4 spaces)

  5. If you are using an IDE, use the formatter and tools that comes with it to organize and clean up your code

  6. Comment your code often. Use Javadoc standards.

  7. Use sensible naming conventions for variable, method and class names.

  8. Use exceptions only if required. Do not use exceptions to handle errors. If errors occur we want the message to propagated up the call stack.

  9. Do not use scriplets in your JSP code. Use JSTL Expression Languages where required.

  10. All jsp file names should be in lowercase

  11. All text in JSP's should either come from Database or Resource bundles. No text should be hard coded in HTML

  12. HTML pages should be XHTML Transitional

  13. Validate your HTML pages using w3c validators

  14. All styles should be written in css. No HTML style attributes

  15. If your code causes warnings or errors in other code, fix other code as well. There shouldn't be any code in CVS which has errors or warnings.

Tuesday, January 15, 2008

Unix file compression utilities

Unix file compression utilities: Creating a tape archive: tar -cf archive.tar myDirectories/ Listing the contents of an archive: tar -tf archive.tar Extracting all files from an archive: tar -xf archive.tar To extract just partial pieces from the archive, supply a file or directory name after the archive name. You can list as many as desiered here, separated by spaces. tar -xf archive.tar filename Compress: gzip archive.tar Decompress: gunzip archive.tar.gz Merging commands The "z" flag works with gzip, to either create a tar/gzipped archive: tar -czvf archive.tgz files/ Decompress a tar/gzipped archive: tar -xzvf archive.tgz

Friday, January 11, 2008

vi Commands

Undo Command

u undo the last command.

Screen Commands

CTL/F Pages forward one screen.

CTL/B Pages back one screen.

>> Indent right

<< Indent left

Cursor Positioning Commands

0 Moves cursor to beginning of current line.

$ Moves cursor to end of current line.

nG Moves cursor to beginning of line n. Default is last line of file.

:n Moves cursor to beginning of line n.

/pattern Moves cursor forward to next occurrence of pattern.

?pattern Moves cursor backward to next occurrence of pattern.

n Repeats last / or ? pattern search.

N Repeats last / or ? pattern search in opposite direction

:.= Print line number of current line

Text Insertion Commands

a Appends text after cursor.

A Appends text at the end of the line.

i Inserts text before cursor.

I Inserts text at the beginning of the line.

Text Deletion Commands

x Deletes current character.

dd Deletes current line.

d) Deletes the rest of the current sentence.

D, d$ Deletes from cursor to end of line.

P Puts back text from the previous delete.

Changing Commands

~ Changes case of current character.

J Joins current line with next line.

Cut and Paste Commands

yy Puts the current line in a buffer. Does not delete the line from its current position.

p Places the line in the buffer after the current position of the cursor.

Appending Files into Current File

:R filename Inserts the file filename where the cursor was.

Exiting vi

ZZ Exits vi and saves changes.

:wq Writes changes to current file and quits edit session.

:q! Quits edit session (no changes made).

Visual mode commands

v Start/stop visual mode Allows you to select a block of text

> shift the block right one shiftwidth

< shift the block left one shiftwidth

y yank ( copy ) the block ( paste with a p )

d delete the block

c change the block


Thursday, October 4, 2007

Ctrl - S

If mistakenly typed Control S at vi terminal, and the terminal stops responding type control Q to resume CTL-S Stop transmission to your terminal. CTL-Q Restart transmission to your terminal.

Tuesday, December 26, 2006

Search for a string in a selection of files

How to search for a string in a selection of files (-exec grep ...). find . -exec grep "www.athabasca" '{}' \; -print This command will search in the current directory and all sub directories. All files that contain the string will have their path printed to standard output. If you want to just find each file then pass it on for processing use the -q grep option. This finds the first occurrance of the search string. It then signals success to find and find continues searching for more files. find . -exec grep -q "www.athabasca" '{}' \; -print This command is very important for process a series of files that contain a specific string. You can then process each file appropriately. An example is find all html files with the string "www.athabascau.ca". You can then process the files with a sed script to change those occurrances of "www.athabascau.ca" with "intra.athabascau.ca".

Monday, September 25, 2006

Shell Script to Bounce resin and Apache eligently

bash-2.05b$ more /etc/init.d/webfe #!/bin/sh # Startup script for syndicated services web front end # . /home/syndprod/.profile case "$1" in start) /opt/oracle/Apache/Apache/bin/apachectl start su syndprod -c "/internet/apps/resin/bin/httpd.sh start" ;; stop) /opt/oracle/Apache/Apache/bin/apachectl stop su syndprod -c "/internet/apps/resin/bin/httpd.sh stop" ;; restart) /opt/oracle/Apache/Apache/bin/apachectl restart su syndprod -c "/internet/apps/resin/bin/httpd.sh stop" su syndprod -c "/internet/apps/resin/bin/httpd.sh start" ;; condrestart) ;; *) echo $"Usage: -zsh {start|stop|restart}" exit 1 esac exit 0