• Shortcuts : 'n' next unread feed - 'p' previous unread feed • Styles : 1 2

» Publishers, Monetize your RSS feeds with FeedShow:  More infos  (Show/Hide Ads)


Date: Thursday, 20 Oct 2011 17:04

Find node from node tree with given path and level. Code passes all my tests (might be that my tests wont cover all possible scenarios), but I would like to know if there is something wrong with my code and if this code could be made shorter and better.

Path is for example String "/home/blog/" and then it is splitted to array by /.

Node has nodePath that cannot contain char /.

If Node has children, but none of them matches, then last matched parent will be returned.

public static Node getNode(Node node, String[] path, Integer level)
{
	if(path.length == 0) return node;
	Integer deepestLevel = path.length - 1;
	String levelPath = path[level];
	String nodePath = node.getNodePath();
	if(node.getChildren().size() == 0)
	{
		if(nodePath.equals(levelPath))
		{
			return node;
		}
	}
	else
	{	
		if(nodePath.equals(levelPath))
		{
			for(Node child : node.getChildren())
			{								
				Integer newLevel = level + 1;
				if(deepestLevel < newLevel) continue;						
				if(child.getNodePath().equals(path[newLevel]))
				{
					if(child.getChildren().size() > 0)
					{
						Node n = getNode(child, path, newLevel);
						if(n != null)
						{
							return n;
						}
						else
						{
							return child;
						}
					}
					else
					{
						return child;
					}
				}
			}
		}
	}
	return null;
}
Author: "https://www.google.com/accounts/o8/id?id=AItOawmFSLiGcm1Ba0EuaqU8GjXQahkn4ZHsvkI"
Send by mail Print  Save  Delicious 
Date: Friday, 23 Sep 2011 20:45

My assignment is Rational Numbers

Create a Rational number class in the same style as the Complex
number class created in class. That is, implement the following
methods: constructor
add
sub
mul
div
toString

You must also provide a Main class and main method to fully test
your Rational number class.

Below is what i have tried so far. I am not looking for someone to do it for me just need some help to point me in the right direction pls.

public class Main {

	public static void main (String[] args) {

		Rational a = new Rational (2,3);
		Rational b = new Rational (8,9);
		
		System.out.println(a + " + " + b + " = "  + a.add(b));
		System.out.println(a + " - " + b + " = "  + a.sub(b));
		System.out.println(a + " * " + b + " = "  + a.mul(b));
		System.out.println(a + " / " + b + " = "  + a.div(b));
	}
}


public class Rational {

	public Rational (int num, int den) {

		numerator = num;
		denominator = den;
	}

	public Rational add (Rational o) {

		return new Rational (numerator + o.numerator, denominator + o.denominator);
	}

	private Rational conjugate () {
		
		return new Rational (numerator, - denominator);
	}
	
	public Rational div (Rational o) {

		return new Rational ((numerator/denominator) / (numerator/denominator), denominator);
	
	
	}
	public Rational mul (Rational o) {
		
		return new Rational (numerator * o.numerator, denominator * o.denominator);
	

	}
	public Rational sub (Rational o) {
	
		return new Rational (numerator - o.numerator, denominator - o.denominator);
	}

	public String toString() {

		return "(" + numerator + " / " + denominator + "i)";
	}
	
	private int numerator;
	private int denominator;
Author: "darteaga.myopenid.com"
Send by mail Print  Save  Delicious 
Date: Sunday, 18 Sep 2011 05:35

A Concept has x number of parents. This code recursively gets the parent concepts and adds them to a list before iterating over the list to get the name of each concept building up a String. I wondered if you could remove the first part where you build up a list and just recurse over the parents getting the name and building up a StringBuffer. But note the call to Collections.reverse(parents);

public String getConceptPath(Concept concept){
		StringBuffer path = new StringBuffer();
		
		if(concept.getParentConcept() == null){
			return concept.getName();
		}
		
		List<Concept> parents = getParentConcepts(concept.getParentConcept());
		Collections.reverse(parents);
		
		for(Concept parentConcept : parents){
			path.append(parentConcept.getName());
			path.append("->");
		}
		
        return path.append(concept.getName()).toString();
	}
	
	public List<Concept> getParentConcepts(Concept concept){
		List<Concept> list = new ArrayList<Concept>();
		list.add(concept);
		if(concept.getParentConcept()!=null){
			list.addAll(getParentConcepts(concept.getParentConcept()));
		}
		
		return list;
	}
Author: "https://www.google.com/accounts/o8/id?id=AItOawnvtFGh-r9ibK5ZHTYiZh2UzxDww7-bwI0"
Send by mail Print  Save  Delicious 
Date: Tuesday, 06 Sep 2011 20:07

Perhaps this could be refactored somehow using a generic method signature into one method?

	public static String serializeNodesAsJson(List<NavigationNode> nodes) throws IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
		ObjectWriter objectWriter = objectMapper.defaultPrettyPrintingWriter();
		StringWriter stringWriter = new StringWriter();
		objectWriter.writeValue(stringWriter, nodes);
		return stringWriter.toString();
	}
	
	public static String serializeSitemapListAsJson(List<SitemapUri> sitemapUris) throws IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
		ObjectWriter objectWriter = objectMapper.defaultPrettyPrintingWriter();
		StringWriter stringWriter = new StringWriter();
		objectWriter.writeValue(stringWriter, sitemapUris);
		return stringWriter.toString();
	}
Author: "https://www.google.com/accounts/o8/id?id=AItOawnvtFGh-r9ibK5ZHTYiZh2UzxDww7-bwI0"
Send by mail Print  Save  Delicious 
Date: Sunday, 12 Jun 2011 21:21

I am new to Java and I have been going crazy trying to get this to work.
I have been trying to get this Print Method to work for the last couple of hour but I just can't figure out what is wrong with it. I don't get any errors when I run it. I only want one output box to display after all of the calculations have been made.
I need to ask the user the following information and display the output for the following:
Number of loans to compare
House Price
Down Payment

My Problem: Something is a matter with my math and the output box is displaying more than once.

I greatly appreciate any help I can get with this. Thanks In Advance!

    package javamortgagecalculator;
import javax.swing.JOptionPane;

public class JavaMortgageCalculator {

     public static void main(String[] args) {
        int numberOfLoans;
        double sellingPrice;
        double downPayment;
        double loanAmount;
        double annualInterestRate = 0.0;
        int numberOfYears = 0;
        double[] interestRatesArr;
        int[] numberOfYearsArr;
        double[] monthlyPayment;
        
        //A. Enter the Number Of Loans to compare and Convert numberOfLoansString to int
        String numberOfLoansString = JOptionPane.showInputDialog("Enter the Number Of Loans to Compare");
        numberOfLoans = Integer.parseInt(numberOfLoansString);

        //B. Enter the Selling Price of Home Convert homeCostString to double
        String sellingPriceString = JOptionPane.showInputDialog("Enter the Loan Amount");
        sellingPrice = Double.parseDouble(sellingPriceString);

        //C. Enter the Down Payment on the Home
        String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home");
        downPayment = Double.parseDouble(downPaymentString);

        //Get the loanAmount by Subtracting the Down Payment from homeCost
        loanAmount = sellingPrice - downPayment;

        interestRatesArr = new double[numberOfLoans];
        numberOfYearsArr = new int[numberOfLoans];
        monthlyPayment = new double[numberOfLoans];
        int counter = 1;

        for (int i = 0; i < numberOfLoans; i++) {
            //Enter the Interest Rate
            String annualInterestRateString = JOptionPane.showInputDialog("Enter the interest rate for Scenario " + counter);
            annualInterestRate = Double.parseDouble(annualInterestRateString);
            interestRatesArr[i] = (annualInterestRate);

            //D2 Get the number of years
            String numberOfYearsString = JOptionPane.showInputDialog("Enter the number of years for Scenario " + counter);
            numberOfYears = Integer.parseInt(numberOfYearsString);
            numberOfYearsArr[i] = (numberOfYears);

            counter++;
        }

        printArray(numberOfLoans,
        sellingPrice,
        downPayment,
        loanAmount,
        annualInterestRate,
        numberOfYears,
        interestRatesArr,
        numberOfYearsArr,
        monthlyPayment);

    }

     
    //public static void printArray(int numOfLoans, double price, double dwnPayment, double loanAmt, double[] printRate, int[] printYears) {
        
      public static void printArray(int numberOfLoans2,
        double sellingPrice2,
        double downPayment2,
        double loanAmount2,
        double annualInterestRate2,
        int numberOfYears2,
        double[] interestRatesArr2,
        int[] numberOfYearsArr2,
        double[] monthlyPayment2){
        
        
        for (int i = 0; i < numberOfLoans2; i++) {
            //Calculate monthly payment
            double monthlyPayment = loanAmount2 * annualInterestRate2 / (1 - 1 / Math.pow(1 + annualInterestRate2, numberOfYears2 * 12));
            //Format to keep monthlyPayment two digits after the decimal point
            monthlyPayment = (int) (monthlyPayment * 100) / 100.0;
            //Store monthlyPayment values in an array
            monthlyPayment2[i] = (monthlyPayment);

            //Calculate total Payment
            double totalPayment = monthlyPayment2[i] * numberOfYears2 * 12;
            
            //Format to keep totalPayment two digits after the decimal point
            //totalPayment = (int) (totalPayment * 100) / 100.0;
            //totalPaymentArray[i] = (totalPayment);

            StringBuilder sb = new StringBuilder();
            int n = 0;
            for (int x = 0; x < numberOfLoans2; x++) {
                if (n == 0) {
                    sb.append(String.format("%s\t\t %s\t\t %s\t\t %s\t\t %s\t\t %s\t\t %n", "Selling Price", "Down Payment", "Loan Amount", "Rate", "Years", "Payment"));
                }
                sb.append(String.format("%s\t\t\t\t %s\t\t\t\t\t\t %s\t\t\t\t\t\t\t\t %s\t\t\t\t\t\t\t\t %s\t\t\t\t\t\t %s\t\t\t\t %n", "$" + sellingPrice2, "$" + downPayment2, "$" + loanAmount2, interestRatesArr2[i] + "%", numberOfYearsArr2[i], "$" + monthlyPayment2[i]));
                n++;
            }

            String toDisplay = sb.toString();

            JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
        }
        
    }

}
Author: "https://www.google.com/accounts/o8/id?id=AItOawlfsaP0zhaKALANAuldgxQaHqJkHDBxUxg"
Send by mail Print  Save  Delicious 
Date: Sunday, 15 May 2011 08:21

i have only been doing java for 4 days now. i made this program but it is a bit lenthy.

import java.util.Scanner;
public class calculator {
	public static void main(String args []){
		Scanner num= new Scanner(System.in);
		Scanner num2= new Scanner(System.in);
		Scanner sym= new Scanner(System.in);
		double n1, n2, ans, lol;
		int symb;
		lol = 0;
		while(lol < 1){
		System.out.println("Welcome to my calculator.");
		System.out.println("Enter first number:");
		n1 = num.nextDouble ();
		System.out.println("Enter operation (1=+, 2=-, 3=X, 4=/, 5=square):");
		symb = sym.nextInt ();
		if (symb == 5){
			ans = n1 * n1;
			System.out.print("Your answer is: ");
			System.out.println(ans);
		}else{
		
		System.out.println("Enter second number:");
		n2 = num2.nextDouble ();
		switch (symb){
		case 1:
			ans = n1 + n2;
				System.out.print("Your answer is: ");
			System.out.println(ans);
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			break;
		case 2:
			ans = n1 - n2;
				System.out.print("Your answer is: ");
			System.out.println(ans);
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			break;
		case 3:
			ans = n1 * n2;
				System.out.print("Your answer is: ");
			System.out.println(ans);
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			break;
		case 4:
			ans = n1 / n2;
				System.out.print("Your answer is: ");
			System.out.println(ans );
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			break;
			default:
				System.out.println("Sorry, invalid input");
		}
		}
		}
		}
}
Author: "getrshah.myopenid.com"
Send by mail Print  Save  Delicious 
Date: Sunday, 01 May 2011 14:59

I basically want a publicly accessible set of strings that I can match against from any class. The below works, but it's an accumulation of things I read about online...probably a horrible way of doing things and I'd love some friendly pointers on how to better achieve my goal :).

public static final HashSet<String> motorways = (HashSet<String>) Collections.unmodifiableSet(new HashSet<String>(Arrays.asList("AB", "BC", "CE")));
Author: "phil989"
Send by mail Print  Save  Delicious 
Date: Saturday, 05 Feb 2011 09:00

Gauri posted this request for refactoring on http://refactormycode.com/codes/1497-jquery-script-too-many-ifs-and-elses#refactor_554541, but it was trying to hijack Nathan's post there. I've reposted Gauri's request here, because the problem looked interesting.

As best as I can tell, this is actually JSP and not plain Java. I hope people don't scream too loudly that I picked Java as the language.

<div class="companypagecoveringanalyst">
<%
    if(company.isEquityCovered() || company.isCreditCovered()){
        out.write("<table><tr><td valign='top'>");
    }	
    if (company.isEquityCovered()) {
        List<CoveringAnalyst> analysts = company.getEquityCoverageList();
        if (analysts.size() > 0) {
            // CoveringAnalyst analyst = analysts.get(0);
            out.write("<table><tr><td>Equity Analyst:&nbsp; </td>"); 
            boolean firstiteration=true; 
            for(CoveringAnalyst analyst : analysts){
                
                if(!firstiteration)
                    out.write("<tr><td>&nbsp;</td> ");
                     
                    out.write("<td>&nbsp; <a href=\"MorganMarkets?page=analyst_page&sid="												
                            + analyst.getSid()
                            + "\">"
                            + StringEscapeUtils.escapeHtml(analyst.getName()) + "</a></td></tr>");
                        
                    firstiteration=false; 
                        
            }
            out.write("</table>");
        }
        if (!company.isCreditCovered()) {
            out.write("</td></tr></table>");
        }
    }	
    
    if(company.isEquityCovered() && company.isCreditCovered())
        out.write("<td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td valign='top'>");
            
    if (company.isCreditCovered()) {
        List<CoveringAnalyst> analysts = company.getCreditCoverageList();
        if (analysts.size() > 0) {
            // CoveringAnalyst analyst = analysts.get(0);
            out.write("<table><tr><td valign='top'>Credit Analyst:&nbsp; </td>");
            boolean firstiteration=true; 
            for(CoveringAnalyst analyst : analysts){
                            
                if(!firstiteration)
                    out.write("<tr><td>&nbsp;</td> ");
                            
                out.write("<td>&nbsp;<a href=\"MorganMarkets?page=analyst_page&sid="
                        + analyst.getSid()
                        + "\">"
                        + StringEscapeUtils.escapeHtml(analyst.getName()) + "</a></td></tr>");
                            
                firstiteration=false; 
            }
            out.write("</table>");
        }
        if (!company.isEquityCovered()) {
            out.write("</td></tr></table>");
        }
    }
    if(company.isEquityCovered() && company.isCreditCovered())
        out.write("</td></tr></table>");
%>
</div>
Author: "Ants (code.herder@recombulator.net)"
Send by mail Print  Save  Delicious 
Date: Monday, 03 Jan 2011 01:41

This is the first time I submit code,so excuse my mistakes(also my bad english)
So, this code makes a simple jinternal frame and I want to improve it or be told if I'm doing anything wrong(or everything)
I thank your comments.

//Main.java

package forms;

import java.awt.*;
import javax.swing.*;

public class Main {

    static JFrame frame;
    static panel pan;
    static menu men;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                createAndShowGUI();
            }
        });

    }

    public static void createAndShowGUI() {

        UIManager.LookAndFeelInfo look[];
        look = UIManager.getInstalledLookAndFeels();
        try {
            UIManager.setLookAndFeel(look[3].getClassName());
        } catch (Exception ex) {
        }


        frame = new JFrame();
        pan = new panel();
        men = new menu(pan);

        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        frame.getContentPane().add(pan);
        frame.setJMenuBar(men.getMenuBar());

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }
}


//menu.java
package forms;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

public class menu extends JMenuBar implements ActionListener {

    private JMenuBar menuBar = new JMenuBar();
    private LinkedList<JMenu> list = new LinkedList<JMenu>();
    private panel Panel;

    public menu(panel Panel) {

        this.Panel = Panel;

        list.add(newMenu("Archivo", KeyEvent.VK_A));
        list.get(0).add(newMenuItem("Salir", KeyEvent.VK_N, "salir"));
        list.get(0).add(newMenuItem("Formlario 1", KeyEvent.VK_E, "form1"));
        list.get(0).add(newMenuItem("Formlario 2", KeyEvent.VK_J, "form2"));
        list.get(0).add(newMenu("Submenu", KeyEvent.VK_O));
        list.get(0).getItem(3).add(newMenuItem("Salir", KeyEvent.VK_N, "salir"));

        list.add(newMenu("Editar", KeyEvent.VK_D));

        for (int i = 0; i < list.size(); i++) {
            menuBar.add((JMenu) list.get(i));
        }

    }

    private JMenu newMenu(String name, int key) {
        JMenu menu = new JMenu(name);
        menu.setMnemonic(key);
        return menu;
    }

    private JMenuItem newMenuItem(String name, int key, String command) {
        JMenuItem menuItem = new JMenuItem(name);
        menuItem.setMnemonic(key);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(key, ActionEvent.ALT_MASK));
        menuItem.setActionCommand(command);
        menuItem.addActionListener(this);
        return menuItem;
    }

    public JMenuBar getMenuBar() {
        return menuBar;
    }

    protected void quit() {
        System.exit(0);
    }

    public void actionPerformed(ActionEvent e) {
        if ("salir".equals(e.getActionCommand())) {
            quit();
        }else if("form1".equals(e.getActionCommand())){
            Panel.newAlumno();
        }else if("form2".equals(e.getActionCommand())){
            Panel.newmTmp();
        }
    }
}


 //panel.java
package forms;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import javax.swing.JDesktopPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public final class panel extends JPanel {

    private final JDesktopPane desktop = new JDesktopPane();
    private Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    private JPanel p2;
    private JPanel p3;

    public panel() {
        super(new BorderLayout());

        desktop.setBackground(Color.white);

        p2 = new JPanel() {

            @Override
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(new Color(100, 50, 50, 100));
                g.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        p2.setOpaque(true);

        p3 = new JPanel();
        p3.setOpaque(true);

        add(desktop);
        dim.setSize(0.9 * dim.width, 0.8 * dim.height);
        setPreferredSize(dim);

    }

    public void newAlumno() {
        JPanel p1 = new JPanel();
        p1.setOpaque(true);
        //fNuevo.getfNuevo(desktop, p1, WIDTH);
        Alumnos.getAlumnos(desktop, p1, WIDTH);
    }

    public void newmTmp() {
        JPanel p1 = new JPanel();
        p1.setOpaque(true);
        mTmp.getmTmp(desktop, p1, WIDTH);
    }
}


//alumnos.java
package forms;

import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.LayoutStyle;
import javax.swing.border.BevelBorder;

public class Alumnos extends JInternalFrame {

    //referencia a singleton
    private static Alumnos ref;
    //desktop, panel, pos. relativa
    JDesktopPane desktop;
    JPanel panel;
    int idx;
    //componentes swing
    private JButton jButton1;
    private JButton jButton2;
    private com.toedter.calendar.JCalendar jCalendar1;
    private JLabel jLabel1;
    private JPanel jPanel1;
    private JPanel jPanel2;

    public Alumnos() {
        super("alumnos", true, true, true, true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    public static Alumnos getAlumnos(JDesktopPane desktop, JPanel panel, int idx) {
        if (ref == null) {
            ref = new Alumnos();
            ref.desktop = desktop;
            ref.panel = panel;
            ref.idx = idx;
            ref.crearAlumnos();
        }
        return ref;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    @Override
    public void dispose() {
        ref = null;
        super.dispose();
    }

    private void initComponents(GroupLayout layout) {

        jPanel1 = new JPanel();
        jCalendar1 = new com.toedter.calendar.JCalendar();
        jButton1 = new JButton();
        jPanel2 = new JPanel();
        jLabel1 = new JLabel();
        jButton2 = new JButton();

        setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
        setIconifiable(true);

        jPanel1.setBorder(BorderFactory.createTitledBorder("Seccion"));

        jButton1.setText("jButton1");

        GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addContainerGap().addComponent(jCalendar1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)).addGroup(jPanel1Layout.createSequentialGroup().addGap(92, 92, 92).addComponent(jButton1))).addContainerGap(60, Short.MAX_VALUE)));
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addContainerGap().addComponent(jCalendar1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(jButton1).addContainerGap(37, Short.MAX_VALUE)));

        jPanel2.setBorder(BorderFactory.createTitledBorder("Seccion 1"));

        jLabel1.setText("jLabel1");

        jButton2.setText("jButton2");

        GroupLayout jPanel2Layout = new GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(jPanel2Layout.createSequentialGroup().addGroup(jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(jPanel2Layout.createSequentialGroup().addGap(49, 49, 49).addComponent(jLabel1)).addGroup(jPanel2Layout.createSequentialGroup().addGap(29, 29, 29).addComponent(jButton2))).addContainerGap(40, Short.MAX_VALUE)));
        jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(jPanel2Layout.createSequentialGroup().addGap(37, 37, 37).addComponent(jLabel1).addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED).addComponent(jButton2).addContainerGap(145, Short.MAX_VALUE)));

        layout.setHorizontalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(jPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addContainerGap(33, Short.MAX_VALUE)));
        layout.setVerticalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(26, 26, 26).addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false).addComponent(jPanel2, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(jPanel1, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)).addContainerGap(31, Short.MAX_VALUE)));


        actions();
    }

    private void crearAlumnos() {
        GroupLayout layout = new GroupLayout(panel);
        initComponents(layout);
        panel.setLayout(layout);

        if (panel != null) {
            this.setContentPane(panel);
            this.getRootPane().setOpaque(false);
        }

        desktop.add(this);
        this.setOpaque(false);
        this.setVisible(true);
        this.setLocation(120 * idx, 60 * idx);
        this.setSize(500, 300);
        desktop.getDesktopManager().activateFrame(this);
    }

    private void actions() {
        jButton2.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        //jLabel1.setText("hola");
    }
}


Author: "https://www.google.com/accounts/o8/id?id=AItOawk9yXGg8pMkXhmnLcG6ZCFdK0KfTtXB4DA (gdmarav374@gmail.com)"
Send by mail Print  Save  Delicious 
Date: Tuesday, 14 Dec 2010 11:32

The method I have trouble with is called sameCoins (Exercise 7.6), where it checks whether the other purse has the same coins, perhaps in a different order.

EX: Purse[Quarter, Dime, Nickel, Dime] and Purse[Dime, Nickel, Quarter, Dime] are equal.

Here's the code I have so far (which doesn't really work...I've combined my tester class in this as well. In the tester, the first one, Purse E & A should be false. Purse E & D should be true):

import java.util.ArrayList;
public class Purse {

private ArrayList<String> coins, back, b;
private int yes, yep, bleh;

public Purse() {
coins = new ArrayList<String>();

}

//Exercise 7.2

public void addCoin(String coinName) {
coins.add(new String(coinName));
}

public String toString() {
if(coins.size() == 0)
return "Purse[]";

String output = "Purse[";

for(String coin : coins) {
output = output + coin + ",";
}
output = output.substring(0, output.length()-1);
return output + "]";
}

//Exercise 7.3

public void reverse() {
back = new ArrayList<String>();

for(int i = coins.size()-1; i >= 0; i--) {
back.add(coins.get(i));
}

for(int k = 0; k < coins.size(); k++) {
coins.set(k, back.get(k));
}

}

//Exercise 7.4

public void transfer(Purse other) {

while(other.coins.size() != 0) {
coins.add(other.coins.remove(0));
}
}

//Exercise 7.5

public boolean sameContents(Purse other) {
if(coins.size() == other.coins.size()) {
for(int a = 0; a < coins.size(); a++) {
if(coins.get(a).equals(other.coins.ge… {
yes++;
}
}

if(yes == coins.size()) {
return true;
} else {
return false;
}
}

else
return false;
}

//Exercise 7.6

public boolean sameCoins(Purse other) {
if(coins.size() == other.coins.size()) {
for(int y = 0; y < coins.size(); y++) {
for(int z = 0; z < other.coins.size(); z++) {
if(coins.get(y).equals(other.coins.ge… {
coins.remove(y);
}
}
}

if(coins.size() == 0) {
return true;
}
else
return false;
}

else
return false;
}


public static void main(String []args) {

Purse stuff = new Purse();
Purse b = new Purse();
Purse a = new Purse();
Purse c = new Purse();
Purse d = new Purse();
Purse e = new Purse();

//Exercise 7.2

stuff.addCoin("Quarter");
stuff.addCoin("Dime");
stuff.addCoin("Nickel");
stuff.addCoin("Dime");

System.out.println(stuff.toString());

//Exercise 7.3

stuff.reverse();
System.out.println(stuff.toString());

//Exercise 7.4
b.addCoin("Dime");
b.addCoin("Nickel");
stuff.transfer(b);

System.out.println(stuff.toString());
System.out.println(b.toString());

//Exercise 7.5
a.addCoin("Dime");
a.addCoin("Penny");
a.addCoin("Quarter");
a.addCoin("Dime");

c.addCoin("Quarter");
c.addCoin("Dime");
c.addCoin("Nickel");
c.addCoin("Dime");

d.addCoin("Quarter");
d.addCoin("Dime");
d.addCoin("Nickel");
d.addCoin("Dime");

System.out.println("Does Purse A have the same coins as Purse B? " + a.sameContents(b));
System.out.println("Does Purse C have the same coins as Purse D? " + c.sameContents(d));

//Exercise 7.6

e.addCoin("Dime");
e.addCoin("Quarter");
e.addCoin("Nickel");
e.addCoin("Dime");

System.out.println("Does Purse E have the same coins as Purse A? " + a.sameCoins(e));
System.out.println("Does Purse E have the same coins as Purse D? " + e.sameCoins(d));

}

}
Author: "https://www.google.com/accounts/o8/id?id=AItOawlEeW5NfSyFgNQwkmJXyHtgV0-idTgDlas"
Send by mail Print  Save  Delicious 
Date: Tuesday, 14 Dec 2010 10:26

I try to write classes to scan a directory recurcively and in a multi-thread maner.

The goal is to reuse those classes and only change the processes. Ie: the scanner call the registered processes at the begining of listing a directory, when scanning a file and at the end of the scanning a directory (and all sub directory).

So the end user only need to implement IProcess to scan a directory.

Thanks for your help in the refactoring !

## IProcess
public interface IProcess {

    /**
     * Return true if the file is supported by this process
     * 
     * Example : <code>
     * private Pattern pattern = Pattern.compile("\.mp3$", CASE_INSENSITIVE);
     * 
     * public boolean allowedFile(File file, Context context) {
     * 		return pattern.matche(name).matches();
     * }
	 * </code>
     * 
     * Or : Example : <code>
     * public boolean allowedFile(File file, Context context) {
     * 		return file.getName().endsWith(".mp3");
     * }
	 * </code>
     * 
     * @param file
     * @param context
     * 
     * @return
     */
    boolean allowedFile(File file, Context context);

    /**
     * Method called each time a file that match the allowedFile pattern has been found in the
     * current directory
     * 
     * @param file
     * @param context
     */
    void processedFile(File file, Context context);

    /**
     * Method called before proccessing the first file of a directory
     * 
     * @param context
     */
    void preProcessDir(Context context);

    /**
     * Method called after proccessing the last file of a directory
     * 
     * @param context
     */
    void postProcessDir(Context context);
}

## Context
/**
 * Context
 * 
 * Keep a map of objects linked to the current directory during the scanning process.
 * 
 * Contexts objetcs are chained. A context is linked with the context of it parent directory. If the
 * parent context is null, you are at the top.
 */
public class Context {

    /**
     * Map of objets to store in the context of the current dirrectory
     */
    private final Map<String, Object> context = new HashMap<String, Object>();

    private int nbSubDir = 0;

    /**
     * The current dirrectory
     */
    private final File currentDir;

    /**
     * the context of the parent directory. If null, this is the root context
     */
    private Context parent;

    private boolean working = true;

    private Context(File currentDir) {
        this.currentDir = currentDir;
    }

    private Context(File currentDir, Context parent) {
        this(currentDir);
        this.parent = parent;
        if (this.parent != null) {
            this.parent.nbSubDir++;
        }
    }

    /**
     * Get an object store in the context or null if the object has not been set
     * 
     * @param key
     * @return
     */
    public Object get(String key) {
        return context.get(key);
    }

    /**
     * @return get the current directory
     */
    public File getCurrentDir() {
        return currentDir;
    }

    /**
     * @return get the parent context of the current context. If null you are at the top
     */
    public Context getParent() {
        return parent;
    }

    /**
     * Get a String object store in the context or null if the object has not been set.
     * 
     * Could throw a ClassCastException if the object is not a String
     * 
     * Same as calling :<code>
	 * (String) context.get(key);
	 * </code>
     * 
     * @param key
     * @return
     */
    public String getStr(String key) {
        return (String) context.get(key);
    }

    /**
     * Store an Object in the context
     * 
     * @param key
     * @param value
     */
    public void put(String key, Object value) {
        context.put(key, value);
    }

    public static Context getRootContext(File startDir) {
        return new Context(startDir);
    }

    public Context getSubContext(File subDir) {
        return new Context(subDir, this);
    }

    public void terminate() {
        if (parent != null) {
            parent.nbSubDir--;
        }
    }

    public boolean isTerminate() {
        return !working && nbSubDir == 0;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "Context=[" + this.currentDir.getAbsolutePath() + ", " + this.nbSubDir + ", "
                + this.working + "]";
    }

    /**
     * 
     */
    public void stopWorking() {
        this.working = false;
    }
}

## Refresher
public class Refresher {

    /**
     * Number of Threads in the pool
     */
    private static final int THREAD_POOL_SIZE = 3;

    /**
     * List of processes to call when scanning a file or a directory
     */
    protected final List<IProcess> processes = new ArrayList<IProcess>();

    private final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

    /**
     * Debuging info
     */
    protected long start;
    protected long end;

    public Refresher() {
    }

    /**
     * Add a process to deal with file and directory
     * 
     * @param process
     */
    public void addProcess(IProcess process) {
        if (process != null) {
            processes.add(process);
        }
    }

    /**
     * Remove a processes
     * 
     * @param process
     */
    public void removeProcess(IProcess process) {
        processes.remove(process);
    }

    /**
     * Run the scan one one or more directory
     * 
     * @param startDir
     */
    public void processed(File... startDir) {
        if (processes.size() == 0) {
            throw new IllegalStateException("One proccess or more is needed");
        }

        if (startDir == null) {
            throw new IllegalArgumentException("startDir cannot be null");
        }

        start = System.currentTimeMillis();

        for (File f : startDir) {
            executeContext(Context.getRootContext(f));
        }
    }

    /**
     * Launch a thread to scan the sub directory
     * 
     * @param context
     */
    protected void executeContext(Context context) {
        executorService.execute(new Execute(this, context));
    }

    /**
     * Ask to stop the thread pool
     */
    public void shutdown() {
        executorService.shutdown();
    }

    /**
     * Call all the processes to deal with a file
     * 
     * @param file
     * @param context
     */
    protected void innerProcessedFile(File file, Context context) {
        for (IProcess process : processes) {
            if (process.allowedFile(file, context)) {
                process.processedFile(file, context);
            }
        }
    }

    /**
     * Call all the process when enter to a new directory
     * 
     * @param context
     */
    protected void innerPreProcessDir(Context context) {
        for (IProcess process : processes) {
            process.preProcessDir(context);
        }
    }

    /**
     * Call all the process xhen all the sub-directory of the current directory have been scanned
     * 
     * @param context
     */
    protected void innerPostProcessDir(Context context) {
        for (IProcess process : processes) {
            process.postProcessDir(context);
        }
    }
}

/**
 * Execute Private class that will be launch in a thread
 */
class Execute implements Runnable {

    private final Context context;
    private final Refresher refresher;

    Execute(Refresher refresher, Context context) {
        this.refresher = refresher;
        this.context = context;
    }

    /**
     * Parse a directory
     */
    public void run() {
        refresher.innerPreProcessDir(context);

        File dir = context.getCurrentDir();
        String[] files = dir.list();
        if (files != null && files.length > 0) {

            for (String file : files) {
                if (file != "." && file != "..") {
                    File currentFile = new File(dir, file);
                    if (currentFile.isDirectory()) {
                        refresher.executeContext(context.getSubContext(currentFile));
                    } else {
                        refresher.innerProcessedFile(currentFile, context);
                    }
                }
            }
        }
        context.stopWorking();

        // if the scan is terminated
        Context c = context;
        while (c != null && c.isTerminate()) {
            refresher.innerPostProcessDir(c);
            c.terminate();
            c = c.getParent();
        }

        // if we are on the root dir, we stop the treads
        if (c == null) {
            refresher.shutdown();

            refresher.end = System.currentTimeMillis();
            System.out.println("Fin en " + (refresher.end - refresher.start) + "ms");
        }
    }
}

## Main class
public class Test {
    public static void main(String[] args) {
        Refresher refresher = new Refresher();
        refresher.addProcess(new Mp3Process());

        refresher.processed(new File(
                "d:\\data\\My Music"));
    }
}


Author: "https://www.google.com/accounts/o8/id?id=AItOawn60BQ3j2wGqeAmwsTZFdMd0YURb5dAR2s"
Send by mail Print  Save  Delicious 
Date: Friday, 29 Oct 2010 18:37

Posted to java because I guess more users here. Clojure code to read Nintendo DS title from ROM file. Read offset first, get UTF-16 title. I don't like wrap's, any solution?

(defn get-romname
  "Return bytes of ROM name"
  [filename]
  (let [bytes (byte-array 260)
        file (RandomAccessFile. filename "r")
        _ (doto file (.seek 0x68) (.read bytes 0 4))
        offset (-> (ByteBuffer/wrap bytes 0 4)
                   (.order ByteOrder/LITTLE_ENDIAN)
                   (.getInt 0))
        eng-offset (+ offset 832)
        _ (doto file (.seek eng-offset) (.read bytes 0 256))
        charset (Charset/forName "UTF-16LE")]
    (-> (.decode charset (ByteBuffer/wrap bytes 0 256))
        (str))))
Author: "edbond (edbond@gmail.com)"
Send by mail Print  Save  Delicious 
Date: Monday, 25 Oct 2010 19:04

test - just to see how it works ;)

:)
Author: "pzielinski.myopenid.com"
Send by mail Print  Save  Delicious 
Date: Monday, 18 Oct 2010 17:04

Any sort of refactoring like use this rather than this, etc...

package reversestring;

public class Propogate {
  public static String reverse(String name) {
    if (name == null || name.length() == 0) {
      throw new RuntimeException("Empty name!");
    }
    return new StringBuilder(name).reverse().toString();
  }

  public static void main(String[] args) {
    String name;
    try {
      name = Propogate.reverse("java");
        System.out.println("Reversed string: " + name);
    } catch (RuntimeException rx) {
        System.err.println(rx.getMessage());
    } finally {
        System.out.println("done");
    }
  }
}
Author: "suhass.myopenid.com (suhasbhushan00754@gmail.com)"
Send by mail Print  Save  Delicious 
Date: Saturday, 16 Oct 2010 13:38

I have created this simple String splitter for blackberry application.

PS: parameterized generic type Enumeration<E> are not present in blackberry.

import java.util.Enumeration;


public class Splitter implements Enumeration{

	private String text;
	private String delim;
	private int startIndex, endIndex;
	
	public Splitter(String text, String delim){
		this.text = text;
		this.delim = delim;
		endIndex = text.indexOf(delim);
		if(endIndex == -1){
			endIndex = text.length();
		}
	}
	
	public boolean hasMoreElements() {
		
		return endIndex > startIndex;
	}

	
	public Object nextElement() {
		String element = text.substring(startIndex, endIndex);
		startIndex = endIndex + delim.length();
		endIndex = text.indexOf(delim,startIndex);
		if(endIndex == -1){
			endIndex = text.length();
		}
		return element;
	}
	public int getElementCount(){
		int count = 1;
		int index = 0;
		for (int i = 0; i < text.length();) {
			index =text.indexOf(delim,i);
			if(index != -1){
				count++;
				i = index + delim.length();
				
			}else{
				break;
			}
			
		}
		return count;
	}
	public String[] getArray(){
		String[] elements = new String[getElementCount()];
		for (int i = 0; hasMoreElements(); i++) {
			elements[i] = (String) nextElement();
		}
		return elements;
		
		
	}

}
Author: "https://www.google.com/accounts/o8/id?id=AItOawmbSmAnfuzMdjmvrzZsJpet_pTqQ2fjGdg (vivart.pandey@gmail.com)"
Send by mail Print  Save  Delicious 
Date: Wednesday, 25 Aug 2010 19:58

Having a table with pairs of "key, data"

I can access data through key, but I want to acces key by data..

(I know data "could" be repeated, but this data isn't, because it's checked when add)

I would like to know if it can be optimize for speed

    final private static Map<String,DataType>  table=new HashMap <String,DataType>();
    
    ///..
 
    String getKeyByData(String data)
    {
         String ret="";

         for (Entry<String,DataType> entry : table.getEntry()) 
         {
             if (entry.getValue().equals(data)) 
             {
                 ret=entry.getKey();
                 break;
             }
         }

         return ret;
    }
Author: "hernan (hernan_eche@yahoo.com.ar)"
Send by mail Print  Save  Delicious 
Date: Saturday, 31 Jul 2010 18:45

I have a map of strings where the values are strings that may contain one or more CSS class names separated by spaces. I want to make sure that each of the class names is valid. If a class is found to be invalid it will be replaced with nothing.

// Check to make sure value is non-null and matches CSS grammar
// A property may contain more than one class name so we need to
// check each potential class name in the string.
for (Map.Entry<String, String> entry : chromeCssProps.entrySet()) {
	String property = entry.getValue();

	if (property == null) {
		property = "";
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("Property was null: " + entry.getKey());
		}
	} else {
		String[] classNames = property.split("\\s+");
		for (String s : classNames) {
			if (!s.matches("-?[_a-zA-Z]+[_a-zA-Z0-9-]*")) {
				property = property.replace(s, "");
				if (LOGGER.isInfoEnabled()) {
					LOGGER.info("Invalid CSS class name in "
							+ entry.getKey() + ": "
							+ s);
				}
			}
		}
	}

	entry.setValue(property);
}
Author: "Zack Mulgrew (maxamor@gmail.com)"
Send by mail Print  Save  Delicious 
Date: Thursday, 15 Jul 2010 09:53

Figures out the current full package name and keeps a stack of package names to parallel the DOM traversal and maintain context between elements.

<test basePackage="com.rmc">
<package name="misc">
</package>
</test>

private LinkedList<String> basePackages;

private String getAttribute( Node node, String name )
{
  // .....
}

private String getBasePackage( org.w3c.dom.Node node )
{
	final String name;
	if ( node.getNodeName().equals( "package" ) )
	{
		name = this.getAttribute( node, "name" );
	}
	else
	{
		name = null;
	}
	final String basePackage = this.getAttribute( node, "basePackage" );
	if ( basePackage == null )
	{
		if ( node.getNodeName().equals( "package" ) )
		{
			if ( name == null || name.isEmpty() )
			{
				return this.basePackages.peek();
			}
			else
			{
				return this.basePackages.peek() + "." + name;
			}
		}
		else if ( this.basePackages.isEmpty() )
		{
			return "";
		}
		else
		{
			return this.basePackages.peek();
		}
	}
	else if ( basePackage.isEmpty() )
	{
		if ( node.getNodeName().equals( "package" ) )
		{
			if ( !( name == null || name.isEmpty() ) )
			{
				return name;
			}
		}
		return "";
	}
	else if ( node.getNodeName().equals( "package" ) )
	{
		if ( name == null || name.isEmpty() )
		{
			return basePackage;
		}
		else
		{
			return basePackage + "." + name;
		}
	}
	else
	{
		return basePackage;
	}
}
Author: "https://www.google.com/accounts/o8/id?id=AItOawmcK8sVHybv2DEt4Muzx_2tJvN4hJIVK1s"
Send by mail Print  Save  Delicious 
Date: Tuesday, 13 Jul 2010 02:31

There is a very important guaranteed behavior at work here explained by the comment above SingletonHolder. Java classes are loaded and initialized on first access - instantiating the class or accessing one of its static fields or methods for the first time. This is relevant to us because classes are verified by the VM when they are loaded, not before.

source: http://android-developers.blogspot.com/2010/07/how-to-have-your-cupcake-and-eat-it-too.html

public class Singleton {
  // Private constructor prevents instantiation from other classes
  private Singleton() {}

  /**
   * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
   * or the first access to SingletonHolder.INSTANCE, not before.
   */
  private static class SingletonHolder { 
    private static final Singleton INSTANCE = new Singleton();
  }

  public static Singleton getInstance() {
    return SingletonHolder.INSTANCE;
  }
}

Author: "jumar (julien.marbach@gmail.com)"
Send by mail Print  Save  Delicious 
Date: Sunday, 04 Jul 2010 08:09

Hi, I just want to disallow two different implemantations of Pseudo using Pseudonym. Any idea how to do this in a better way than right now?

public class Pseudonym<T extends Pseudo> {
	private T alias;
	private T original;

	public Pseudonym(T alias, T original) {
		if (!alias.getClass().equals(original.getClass()))
			throw new IllegalArgumentException("alias and original must be of same type.");
		this.alias = alias;
		this.original = original;
	}

	public T getAlias() {
		return alias;
	}

	public T getOriginal() {
		return original;
	}
}

interface Pseudo{
  //marker interface
}
Author: "DaJunkie (derkotzer@yahoo.de)"
Send by mail Print  Save  Delicious 
Previous page - Next page
» You can also retrieve older items : Read
» © All content and copyrights belong to their respective authors.«
» © FeedShow - Online RSS Feeds Reader