Thursday, December 28, 2017

SQL: Return the first / top n rows of each group

For example, you have a product table containing the following columns.

Name                Type         
----------            ------------
Apple                Fruit
Banana              Fruit
Walnut               Nut
Papaya               Fruit
Cashew              Nut
Pine Nut             Nut

You want your SQL to return the top 2 rows from each Type, a result like this.

Type                   Name
---------              ------------------------------
Fruit                  Apple
Fruit                  Banana
Nut                    Cashew
Nut                    Pine Nut

The SQLs below shall help.

SQL> select Type, Name
           from (
                           select Type, Name, 
                             ROW_NUMBER() OVER (PARTITION BY Type ORDER BY Type, Name) as type_rank
                           from product
                    ) AS product 
            where type_rank <= 2;

OR

SQL> WITH prequery AS (
                  select Type,
                             Name,
                             ROW_NUMBER() OVER (PARTITION BY Type ORDER BY Type, Name) as type_rank
                  from product
              )
              SELECT Type, Name,
              FROM prequery
              WHERE type_rank <= 2;

----------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


SQL: Concatenate values in each result group as a list; LISTAGG and its alternative

For example, you have a product table containing the following columns.

Name                Type           
----------            ------------
Apple                Fruit
Banana              Fruit
Walnut               Nut
Papaya               Fruit
Cashew              Nut

You want your SQL to return a result like this.

Type                   Names
---------              ------------------------------
Fruit                  Apple, Banana, Papaya
Nut                    Cashew, Walnut

1. Find the version of your Oracle database

          select * from v$version;

2. If your Oracle version is 11.2 or later, the Oracle LISTAGG function can help you to achieve your goal.

SQL> select Type, LISTAGG(coalesce( Name, ' '), ',') WITHIN GROUP (ORDER BY Name) as Names
           from product
           group by Type;

The names can be separated by any character by replacing the comma in LISTAGG(Name, ',') with the character.

3. If you use an Oracle database earlier than release 11.2 and LISTAGG is not available, the following shall work for you.

SQL> select Type, rtrim(xmlagg(xmlelement(e, coalesce( Name, ' '), ', ') order by Name).extract('//text()').getclobval(), ', ') AS Names
           from product
           group by Type;
   

--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, December 27, 2017

SQL: Add single quotes, double quotes or string around a query result value

Lets say you have a Fruit table.

name        price          desc
----------   ---------      ----------------
Apple       1.94           Very popular
Mango      2.05           Popular in Summer

Now, you want to list the fruits and their descriptions and the descriptions be printed with single or double quotes around them. You can either use the string quoting literals introduced in 10g or by concatenating the quotes.

The string quoting literal is to put your string in q'[your string]'.  The square brackets can be replace by { }, < >,  ( ), or ! !.

1. Single quote

SQL> select name, q'[']' || desc || q'[']' from fruit;
or
SQL> select name, q'!'!' || desc || q'<'>' from fruit;
or
SQL> select name, '''' || desc || '''' from fruit;

The '''' is four single quotes

2. Double quote

SQL> select name,  q'["]' || desc || q'["]' from fruit;
or
SQL> select name, q'(")' || desc || q'{"}';
or
SQL> select '"' || desc || '"' from fruit;

The '"' is a double quote surrounded by single quotes.

3. String

Now, you want to add a string "Popularity: " in front of the descriptions.

SQL> select name, q'{Popularity: }' || desc from fruit;
or
SQL> select name, 'Popularity: ' || desc from fruit;

--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, December 22, 2017

Use MethodHandle to dynamically invoke method

MethodHandle is introduced in Java 7. For dynamic method invoking, it is faster than reflection.

In the code below, class MethodHandleTest2 has three JTextField fields and an objModified method. When any of the JTextField fields is modified, the objModified method will be called to handle the modification accordingly.

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MethodHandleTest2 extends JFrame{
    public MethodHandleTest2() {
        JTextField[] data = {new JTextField("Peach", 20),
                                  new JTextField("Papaya", 20),
                                  new JTextField("Mango", 20)};
        JPanel panel = new JPanel(new GridLayout(3, 1));

        for (int i=0; i<data.length; i++){
            try {
                data[i].addActionListener(new ObjectActionListener("objModified",
                                                   new Object[]{this, data[i], "Field "+(i+1)+" Modified"}
                ));
                panel.add(data[i]);
            } catch (NoSuchMethodException e){
                System.out.println(e.getMessage());
            }
        }
        this.add(panel);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(700, 300);
        this.pack();
    }

    public static void main(String[] args){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                (new MethodHandleTest2()).setVisible(true);
            }
        });
    }

    public class ObjectActionListener implements ActionListener {
        private Object[] parameters = null;
        private String methodName = null;

        public ObjectActionListener(String methodName, Object[] parameters)
                throws NoSuchMethodException, SecurityException {
            this.methodName = methodName;
            this.parameters = parameters;
        }

        private MethodHandle getMethod() throws NoSuchMethodException,
                IllegalAccessException {

            //For the objModified method, its return type is void, and it takes
            // a JTextField argument and a String argument.
            MethodType mt = MethodType.methodType(void.class, JTextField.class, String.class);

            //Get the MethodHandle: argument1 is the class where the method is located;
            // argument2 is the method name;
            //argument3 is the method type of the method signature
            MethodHandle mh = MethodHandles.lookup()
                    .findVirtual(MethodHandleTest2.class,
                            methodName,
                            mt);
            return mh;
        }

        @Override
        public void actionPerformed(ActionEvent event) {
            try {
                MethodHandle method = getMethod();
                //The invoke method is supposed to be able to take an array argument.
                //Somehow, it does not work for me in my test code.
               //So, I have to put each component of the array in the arguments.
                method.invoke(parameters[0], parameters[1], parameters[2]);
            } catch (IllegalAccessException e) {
                System.out.println(e.getMessage());
            } catch (InvocationTargetException e) {
                System.out.println(e.getMessage());
            } catch (Throwable e) {
                System.out.println(e.getMessage());
            }
        }
    }

    public void objModified(JTextField obj, String message){
            String text = obj.getText();
            System.out.println(message+": "+text);
    }
}

The code using reflection to do the same job can be found here

--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, December 21, 2017

Java 8: Calculate average, sum, maximum, minimum and count of elements of a list

The easiest way probably is to get the summary statistics of the list through stream first. Get all the values, then, from the summary statistics. Below is an example for a integer list. The same logic applies to all other type of numbers.

List<Integer> intList = Arrays.asList(123, 886, 43, 25, 33, 89);

IntSummaryStatistics intStat = intList.stream()
            .mapToInt ( i -> i)
            .summaryStatistics();

double average = intStat.getAverage();
long sum = intStat.getSum();
long count = intStat.getCount();
int max = intStat.getMax();
int min = intStat.getMin();

Of course, if you just want to get the sum or find the maximum, you can do it like below.

int sum = intList.stream()
           .mapToInt(i -> i)
           .sum();

int max = intList.stream()
           .mapToInt(i -> i)
           .max()
           .orElse(0);

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, December 15, 2017

java 8: Convert a long array to String array


//Convert a primitive long[] to String[]
long[] pla = {1155L, 22334L, 559876L};

String[] spla = Arrays.stream(pla)
              .mapToObj(String :: valueOf)
              .toArray(String[] :: new);

//Convert a boxed Long[] to String[]
Long[] bla = LongStream.of(pla)
               .boxed().toArray(Long[] :: new);

String[] sbla = Arrays.stream(bla)
               .mapToLong(Long::longValue)
               .mapToObj(String::valueOf)
               .toArray(String[] :: new);

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

java 8: Convert a Long number list to a boxed and unboxed primitive array / convert a String list to String array by Stream

To convert a Long list to array, while Long[] ar = list.stream().toArray(size -> new Long[size]) is perfectly fine, long[] par = list.stream().toArray(size -> new long[size]) does not work. The argument of the toArray method, the IntFunction, takes an parameter type that is bound to Object, and long is not an Object while Long is.

The workaround is to map each element in the Stream to a Long so that when the toArray method without argument is called, it returns an long[] instead of an Object[].

import java.util.List;
import java.util.Arrays;

public class StreamListToArray {
    public static void main(String[] args){
        List<Long> list = Arrays.asList(new Long(11238), new Long(55444), new Long(1099886));
       
        Long[] ar = list.stream().toArray(size -> new Long[size]);
        for(Long lg : ar){
            System.out.println(lg);
        }
        System.out.println();

        //Method 1
        long[] ars = list.stream().mapToLong(Long :: new).toArray();
        for(Long lg : ars){
            System.out.println(lg);
        }
        System.out.println();

        //Method 2
        long[] par = list.stream().mapToLong(Long :: longValue).toArray();
        for(long lg : par){
            System.out.println(lg);
        }

        System.out.println();
        List<String> slist = Arrays.asList("String line 1", "String line 2", "String line 3");
       
        String[] sar = slist.stream().toArray(size -> new String[size]);
        for(String s : sar){
            System.out.println(s);
        }
    }
}

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, December 14, 2017

Set up a Timer to repeatedly execute a piece of code or a task or to repeatedly update the state of your objects


Lets say, you have an integer field and you want to increment it by 5 every minute.

public class TimerTest {
      private int theValue = 0;
      private javax.swing.Timer timer1 = null;

      public TimerTest() {
            //Set up the timer to perform the action repeatedly
             //after a delay of 1 minute which is 60000 milliseconds.
            timer1 = new javax.swing.Timer(60000, new TimerAction());
            timer1.start();

      }

      private class TimerAction implements ActionListener {
            @Override
            public void actionPerformed(ActionEvent e) {
                  theValue += 5;
                  System.out.println("The value currently is "+theValue);
            }
      }
}

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Monday, December 4, 2017

Java 8: Three ways to calculate days between two dates

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class DateTest101 {

    public static void main(String[] args){
        String dt2 = "2017335";
        String dt1 = "2016335";
     
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyyDDD");
        LocalDate dat2 = LocalDate.parse(dt2, pattern);
        LocalDate dat1 = LocalDate.parse(dt1, pattern);
        System.out.println("dat2: "+dat2.toString()+", dat1: "+dat1);
     
        //Method 1
        long daysBetween1 = dat1.until(dat2, ChronoUnit.DAYS);
        System.out.println("daysBetween1: "+ daysBetween1);
     
        //Method 2
        long daysBetween2 = ChronoUnit.DAYS.between(dat1, dat2);
        System.out.println("daysBetween2: "+ daysBetween2);
     
        //Method 3
        long daysBetween3 = Duration.between(dat1.atStartOfDay(), dat2.atStartOfDay()).toDays();
        System.out.println("daysBetween3: "+ daysBetween3);
    }
}

Reference:

1. Calculate days between two dates in Java 8

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, November 22, 2017

[Solved] google blog title and comment do not show angle brackets and the content within

You are trying to compose a google blog, and you set your title to "The animals mentioned in <Harry Potter>". After you finished and published your blog, you are surprised to see that the title of your blog becomes "The animals mentioned in", the <Harry Potter> part disappeared.

A set of angle brackets denotes a tag in HTML, therefore is not displayed. The google blog automatically translates angle brackets in the blog content into &lt; and &gt;. For example, <Harry Potter> is translated to &lt;Harry Potter&gt;

The conclusion is that if you want to display angle brackets in your blog title, use &lt; for < and &gt; for >.

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


NetBeans: The <classpath> for <junit> must include junit.jar if not in Ant's own classpath

This error happens because the JUnit jar is missing from your class path. When this error occurs while you are trying to run your project:

1. Right-click on your project, and select Properties.

2. In the popup window, click on the Libraries under the Categories and check if the JUnit jar or library presents.

3. Add the JUnit-x.xx.jar to your library or build it as a library and add the library. You can get the JUnit jar from here.

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Use ComponentListener to resize font when the size of a JPanel / JFrame is changed

After a container is maximized or stretched to a very large size, the initial font may be too small to look nice in the big container. One way to resize the font according to the size of the container is through a ComponentListener. Below is a sample code.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.FontUIResource;

public class PanelFontResize extends JFrame {

    private JPanel thePanel;
    private JLabel theLabel;
    private JTextField theText;
    private JTable theTable;

    public PanelFontResize() {

        theLabel = new JLabel("The Topic: ");
        theText = new JTextField("Does the Sun rise the same time each day?");
        JPanel northPane = new JPanel(new GridBagLayout());
        northPane.add(theLabel, new GridBagConstraints(0,0,1,1,1.0,1.0,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0,0,0,5),0,0));
        northPane.add(theText, new GridBagConstraints(1,0,2,1,2.0,1.0,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,0,0,0),0,0));
     
        String[] colnames = {"Season", "Sun Rise"};
        String[][] data = {{"Spring", "6:00"},
                    {"Summer", "5:30"},
                    {"Autum", "6:30"},
                    {"Winter", "7:00"}};
        theTable = new JTable(data, colnames);
        JScrollPane sp = new JScrollPane(theTable);
     
        thePanel = new JPanel(new BorderLayout());
        thePanel.add(northPane, BorderLayout.NORTH);
        thePanel.add(sp, BorderLayout.CENTER);
        thePanel.addComponentListener(new PanelListener());
     
        setContentPane(thePanel);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);
        validate();
        setVisible(true);
    }
 
 
    private class PanelListener extends ComponentAdapter {

        @Override
        public void componentResized(ComponentEvent e) {
            Dimension psize = thePanel.getSize();
            if (psize.width <= 761 && psize.height <= 551) {
                setFonts(11);
            } else if (psize.width <= 984 && psize.height <= 617
                    && psize.width > 761 && psize.height > 551) {
                setFonts(13);
            } else if (psize.width <= 1046 && psize.height <= 762
                     && psize.width > 984 && psize.height > 617) {
                setFonts(15);
            } else if (psize.width <= 1245 && psize.height <= 867
                    && psize.width > 1046 && psize.height > 762) {
                setFonts(18);
            } else if (psize.width > 1245 && psize.height > 867){
                setFonts(20);
            }
        }
    }
 
    public void setFonts(int fontSize) {

        Font plainFont = new Font("Dialog", Font.PLAIN, fontSize);
        Font boldFont = new Font("Dialog", Font.BOLD, fontSize + 2);

        UIManager.put("Text.font", new FontUIResource(plainFont));
        UIManager.put("TextField.font", new FontUIResource(plainFont));
        UIManager.put("Table.font", new FontUIResource(plainFont));
        UIManager.put("Label.font", new FontUIResource(boldFont));
        UIManager.put("TableHeader.font", new FontUIResource(boldFont));
        UIManager.put("Panel.font", new FontUIResource(plainFont));
        UIManager.put("ScrollPane.font", new FontUIResource(plainFont));
     
        setTableSize(fontSize);
        SwingUtilities.updateComponentTreeUI(thePanel);
    }
 
    private void setTableSize(int fontSize){
            Font f = getFont().deriveFont((float)fontSize);
            theTable.setRowHeight(new Float(f.getSize2D() * 1.5).intValue());
    }
 
    public static void main(String[] args){
        new PanelFontResize();
    }
}

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


Tuesday, November 21, 2017

Use UIManager to set fonts, foreground color, background color, select color, border for Swing components

Once you set the properties in the UIManager, all your Swing components will have the corresponding look and feel.

public void setLookAndFeel () {

        Font plainFont = new Font("Serif", Font.PLAIN, 12);
        Font boldFont = new Font("Serif", Font.BOLD, 12);

        Color focusColor = Color.BLUE;
        Color backgroundColor = Color.YELLOW;
        Color disabledForgroundColor = Color.GREY;
        Color selectColor = Color.LIGHT_GRAY;

        UIManager.put("Text.font", new FontUIResource(plainFont));
        UIManager.put("TextField.font", new FontUIResource(plainFont));
        UIManager.put("FormattedTextField.font", new FontUIResource(plainFont));
        UIManager.put("PasswordField.font", new FontUIResource(boldFont));
        UIManager.put("TextArea.font", new FontUIResource(plainFont));
        UIManager.put("TextPane.font", new FontUIResource(plainFont));
        UIManager.put("List.font", new FontUIResource(plainFont));
        UIManager.put("Table.font", new FontUIResource(plainFont));
        UIManager.put("TableHeader.font", new FontUIResource(plainFont));
                   
        UIManager.put("CheckBox.font", new FontUIResource(plainFont));
        UIManager.put("RadioButton.font", new FontUIResource(plainFont));
        UIManager.put("Button.font",new FontUIResource(boldFont));
        UIManager.put("Button.focus", new ColorUIResource(focusColor));
        UIManager.put("Button.border", new LineBorder(Color.ORANGE, 5, true));
        UIManager.put("ComboBox.font", new FontUIResource(plainFont));
        UIManager.put("ComboBox.TableHeader.font", new FontUIResource(plainFont)); 
        UIManager.put("Label.font", new FontUIResource(plainFont));
        UIManager.put("ToolTip.font", new FontUIResource(boldFont));
        UIManager.put("ToggleButton.font", new FontUIResource(plainFont));
        UIManager.put("TitledBorder.font", new FontUIResource(boldFont));
     
        UIManager.put("Menu.font", new FontUIResource(boldFont));
        UIManager.put("MenuItem.font", new FontUIResource(boldFont));
        UIManager.put("MenuBar.font", new FontUIResource(boldFont));
        UIManager.put("PopupMenu.font", new FontUIResource(boldFont));
        UIManager.put("RadioButtonMenuItem.font", new FontUIResource(boldFont));
        UIManager.put("CheckBoxMenuItem.font", new FontUIResource(boldFont));
        UIManager.put("MenuItem.acceleratorFont", new FontUIResource(boldFont));
        UIManager.put("CheckBoxMenuItem.acceleratorFont", new FontUIResource(boldFont));
        UIManager.put("Menu.acceleratorFont", new FontUIResource(boldFont));
        UIManager.put("RadioButtonMenuItem.acceleratorFont", new FontUIResource(boldFont));
     
        UIManager.put("ToolBar.font", new FontUIResource(boldFont));
        UIManager.put("MenuBar.font", new FontUIResource(boldFont));
        UIManager.put("Panel.font", new FontUIResource(boldFont));
        UIManager.put("ProgressBar.font", new FontUIResource(boldFont));
        UIManager.put("OptionPane.font", new FontUIResource(boldFont));
        UIManager.put("OptionPane.buttonFont", new FontUIResource(boldFont));
        UIManager.put("OptionPane.messageFont", new FontUIResource(plainFont));
        UIManager.put("ScrollPane.font", new FontUIResource(boldFont));
        UIManager.put("EditorPane.font", new FontUIResource(plainFont));
        UIManager.put("ColorChooser.font", new FontUIResource(boldFont));
        UIManager.put("InternalFrame.titleFont", new FontUIResource(boldFont));
        UIManager.put("TabbedPane.font", new FontUIResource(boldFont));

        UIManager.put("Panel.background", backgroundColor);
        UIManager.put("CheckBox.background", backgroundColor);
        UIManager.put("RadioButton.background", backgroundColor);
        UIManager.put ("Button.select", selectColor);
UIManager.put ("ToggleButton.select", selectColor);
        UIManager.put("ComboBox.disabledBackground", backgroundColor);
        UIManager.put("ComboBox.fieldBackground", backgroundColor);
        UIManager.put("ComboBox.disabledForeground", disabledForgroundColor);
        UIManager.put("OptionPane.background", backgroundColor);
        UIManager.put("OptionPane.warningDialog.border.background", backgroundColor);
        UIManager.put("Label.background", backgroundColor);
        UIManager.put("TextField.shadow", backgroundColor);
        UIManager.put("TextField.background", backgroundColor); 
    }

Reference:

1. Swing UIManager Keys
2. Nimbus Defaults

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, November 3, 2017

JLabel: setHorizontalTextPosition vs setHorizontalAlignment

A JLabel can display a text string or an image or both.

The setHorizontalTextPosition(int textPosition) method is used when a JLabel displays both an image and a text. This method specifies whether the text should be displayed on the left or right side or center of the image. It takes an argument which is one of these SwingConstants values: LEFT, CENTER, RIGHT, LEADING or TRAILING. TRAILING is the default position.

The setHorizontalAlignment(int alignment) method is used to specify the alignment of the whole contents on the JLable. It also takes an argument which is one of these SwingConstants values: LEFT, CENTER, RIGHT, LEADING or TRAILING.

For example, you have a JLabel which only displays the text "User Name", and you want the text to be at the right side of the label. You have two ways to achieve this.

1. JLabel userLabel = new JLabel ("User Name", SwingConstants.RIGHT");

2. JLabel userLabel = new JLabel();

      userLabel.setText("User Name"); //by default, JLabel displays text at the left edge.
      userLabel.setHorizontalAlignment(SwingConstants.RIGHT);

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, October 31, 2017

Java: Resize font size automatically when the size of a JLabel is changed

You have JLabels in your Swing GUI interface and are set to fill the empty spaces when the GUI interface is resized. You want the size of the text on the label to change accordingly when the size of the label changes.

One way to do it is to set a range of the text font size, add a ComponentListener to the label and reset the size of the text font. Below is a sample code.

import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class LabelFontResizeTest extends JLabel {
    //The range of the font size
    private static final int MIN_FONT_SIZE = 3;
    private static final int MAX_FONT_SIZE = 240;
    private Graphics g;

    public LabelFontResizeTest(String text) {
        super(text);
        addComponentListener(new LabelListener());
    }

    //The ComponentListener that sets the font size
    private class LabelListener extends ComponentAdapter {

        @Override
        public void componentResized(ComponentEvent e) {
            if (g == null) {
                return;
            }
            Rectangle r = LabelFontResizeTest.this.getBounds();
            int fontSize = MIN_FONT_SIZE;
            Font f = LabelFontResizeTest.this.getFont();

            Rectangle r1 = new Rectangle();
            Rectangle r2 = new Rectangle();
            while (fontSize < MAX_FONT_SIZE) {
                r1.setSize(getTextSize(LabelFontResizeTest.this, f.deriveFont(f.getStyle(), fontSize)));
                r2.setSize(getTextSize(LabelFontResizeTest.this, f.deriveFont(f.getStyle(), fontSize + 1)));
                if (r.contains(r1) && !r.contains(r2)) {
                    break;
                }
                fontSize++;
            }

            setFont(f.deriveFont(f.getStyle(), fontSize));
            repaint();
        }
    }

    private Dimension getTextSize(JLabel l, Font f) {
        Dimension size = new Dimension();
        g.setFont(f);
        FontMetrics fm = g.getFontMetrics(f);
        size.width = fm.stringWidth(l.getText());
        size.height = fm.getHeight();

        return size;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.g = g;
    }

    public static void main(String[] args) throws Exception {
        LabelFontResizeTest label = new LabelFontResizeTest("Magic Text expand and shrinks automatically!!!");
        JFrame frame = new JFrame("Resize label font");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().add(label);

        frame.setSize(300, 100);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}



Reference

1. How to change JLabel font size to fill JPanel free space while resizing?

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Wednesday, October 25, 2017

Java: Conversions between boxed number Integer[] array and unboxed primitive int[] array

int [] unboxed = {3, 6, 9, 12, 15, 18, 21, 24, 27};

Integer [] boxed = IntStream.of(unboxed).boxed().toArray(Integer[]::new);

int [] unboxed2 = Stream.of(boxed).mapToInt(Integer::intValue).toArray();

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Java: Convert List to primitive Array long[] ; and primitive Array long[] to List

For instance, you have a list of Long object.

        List<Long> list = <your list>;

You want to convert it to a long[].

1. Java 8
 
        Convert the list to a Stream<Long>, map each Long object to long, and then convert the result to an array.

        long[] array = list.stream().mapToLong(Long::longValue).toArray();

2. Before Java 8 versions

        Created an empty array with the size of your list, loop through the list and add each element to the array.

         long [] array = new long[list.size()];
         int i = 0;
         for (long element : list) {
                 array[i++] = element;
         }

Now you have a long[] array2 object and you want to convert it to a List<Long> object.

3. Java 8

        List<Long> list2 = Arrays.stream(array2).boxed().collect(Collectors.toList());

4. Before Java 8 versions.

        List<Long> list2 = new ArrayList<>();
        for (long value : array2) {
                list2.add(new Long(value));
        }

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, September 15, 2017

SQL*Plus: Copy a table from one user to another user

1. Log in SQL*Plus as SYSDBA

SQL> connect <oracle user> as SYSDBA;
password:

2. Grant the user with privilege to the table space

SQL> GRANT UNLIMITED TABLESPACE TO <oracle user>;

Grant succeeded.

3. Copy the table from schema 2 to schema 1.

SQL> create table <schema1>.<tablename> as select * from <schema2>.<tablename>;

Table created.

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, September 14, 2017

Huawei Nexus 6P: Block calls from a phone number

If you just received a phone call which you feel annoying and decide not to receive further calls from that number. You can block it.

1. Tap the phone icon on your screen
2. Select the call history tab (the clock icon on top)
3. Press and keep holding your finger on the phone number util a pop-up menu is shown.
4. Select "Block Number", and then "Block"

To unblock it:

Press and keep holding your finger on the phone number, select "Unblock Number", and then "Unblock".

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


Wednesday, September 13, 2017

Oracle: Copy schema from one user to another user

Here are the steps to copy schema from one user to another.

1. Unlock the source Oracle user account. Login Oracle as SYSDBA and execute the following command.

SQL> Alter user <fromUsername> identified by <fromPassword> account UNLOCK;

2. Create the directory where you would like to export the schema.

SQL> CREATE OR REPLACE DIRECTORY schema_dump AS '/usr/myDirectory/oracleSchema';
SQL> GRANT READ, WRITE ON DIRECTORY schema_dump TO <user need to access>;

The schema_dump is a name you can use in your command. The physical location of the directory is '/usr/myDirectory/oracleSchema'.

quit SQL*Plus.

3. Export the source schema to the dump directory.

$ expdp <fromUsername> <fromPassword> schemas=<schema name> directory=schema_dump dumpfile=schema.dmp logfile=dumplog.txt

The <fromUsername> is the source user Oracle login username and the <fromPassword> is the source user Oracle login password.

4. Import the schema and map the schema to the destination user.

$ impdp <toUsername> / <toPassword> directory=schema_dump dumpfile=schema.dmp logfile=dumplog.txt remap_schema=<fromUserSchemaName>:<toUserSchemaName>

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, September 8, 2017

SQL*Plus: Format column width to display a column at a specified length

Lets say that you have a FRUIT table with the following schema.

Name                      Type
-----------------         ---------------------------
NAME                      VARCHAR2(100)
PRICE                       NUMBER
DESC                        VARCHAR2(100)

Since most of the names of your fruits are far more less than 100 characters, there is a big empty space after each name in your query result, and you want to reduce that.

SQL> COLUMN Name FORMAT A50
SQL> select * from FRUITS;

This will reduce the Name column in your query result to 50 characters. Any name longer than 50 characters is truncated.

Reference:
1. Formatting SQL*Plus Reports

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.