Float to []byte

If I have this float (6.061.970.311.763.627), how to do for get an array of byte from this float (0x158954731256AB)?
There is not problem if it is a String ("158954731256AB") or two integer (0x00158954 0x731256AB).

jotremar wrote:
It is for a network protocol. It only work with bytes. All numbers are in different endianess.
If a want to send a int (4, for example), I have to send it with endianess (0x04000000). This protocol have numbers more great than int (I use float for it) Do NOT use float just to get numbers bigger than int. For one thing there will be holes--integers that are in float's range that can't be represented by float. ONLY use float or double if you want floating point numbers. If you just need bigger integers, stick to long or BigInteger.
and I have to make endianess to it (0x0400000000000000 => float = 4).That's wrong for two reasons.
1. Float is 4 bytes, just like int.
2. For the third bluddy time, 4 in a Java float is NOT 0x00000004. It is 0x40800000. A float's bite pattern for an integer is NOT the same as an int's bit pattern for the same integer.
Okay, three reasons, but I already told you the third, and it kind of goes along with #1 anyway, but I'll repeat it:
3. There are integers that int can represent that float cannot. And there are integers outside of int's range, but still in float's range that float cannot represent.
[SOME THINGS YOU SHOULD KNOW ABOUT FLOATING-POINT ARITHMETIC|http://java.sun.com/developer/JDCTechTips/2003/tt0204.html#2]
[What Every Computer Scientist Should Know About Floating-Point Arithmetic|http://docs.sun.com/source/806-3568/ncg_goldberg.html]
[Another good (slightly simpler) FP explanation|http://mindprod.com/jgloss/floatingpoint.html]
Edited by: jverd on Sep 10, 2009 3:43 PM

Similar Messages

  • Float word byte order?

    I'm attempting to build the "cairo" library for FlasCC. The "./configure" step is hitting an issue - it's trying to determine what the float word byte order is (I'm not sure, by the way, whether this is terribly critical for actually compiling the library...) In any case, the method they are using isn't working with FlasCC.
    Can perhaps a FlasCC developer chime in and let me know what the float word byte order is (little- or big-endian)?
    Thanks!

    FlasCC is little endian.

  • Float to byte - String to byte

    Hi All,
    I am writing a Binary file writer.
    the convertion is made from several java type (int, float, double, String, ...) to bytes equivalent.
    I have a reader that reads the files that I am generating through my prog.
    In some fields, i put 0.0f value once It is read it return some weird values like 9.66338e-13
    how can solve this problem ?
    thanks in advance

    If you take time to read it would ne better...and you can help efficiently...
    the thing i don't want to talk in depth details...
    There is a telecom system which read a binary file. with a specific format...in that format, there is some fields with float type.
    And there is whole bunch of checkin to validate the type and the format and the size of each field...
    I am writing an app that generate those files...in fact, they are generated
    and also read by the T-system...but in the float fields, the data which is supposed to be 0.0f is something else.
    So the question, should i fix something with float type to get the expected result...like precision for exampl..or i do not know...
    And none have said it's a java problem...
    it's just the matter i have missed something...
    Hope you got it...
    thanks for help...and not blabla

  • Float to bytes

    (I searched the forum but had no luck)
    I urgently need to know how to convert a float(or double) to 4 bytes(IEEE format)
    Thanks

    either Float(yourFloatValueHere).floatToIntBits() or Float(yourFloatValueHere).floatToRawIntBits(). Check the APi for more info.

  • Byte[] to float?

    Hi,
    I'm trying to write an applet which talks to its parent server. The server sends a series of floats (4 bytes each) to the applet, which is stored to a byte array by BufferedInputStream.read(buffer, 0, 4). I need to convert those 4-byte-sized byte array to a float like this:
    float Number = (float)ByteArray; // Doesn't work!
    Is there any helper functions in java to do this? Or should I send the numbers as plain text through the network, and then convert from String to float instead? (Obviously I don't wanna do that due to great performance hit)
    Any help would be greatly appreciated. Thanks!
    Aaron

    It is possible to convert a byte array to a float:
    * Converts an array of bytes to a float.
    * @param arr  an array of 4 bytes to be converted
    * @return a float value comprising the bytes in
    static float byteArrayToFloat(final byte[] arr) {
       int bits = (arr[0] << 24) | (arr[1] << 16) |
                    (arr[2] << 8) | arr[3];
       return Float.intBitsToFloat(bits);
    }But why not just use a DataInputStream?

  • Converting Byte [] into float []

    Hi, I read the contents of a file into a byte array and am now trying to convert it into a float array.
    here is the code I am using
    public static float [] bytetofloat(byte [] convert){
        float [] data = new float [convert.length/2];
        for(int i = 0;i<convert.length;i+=2){
            for(int j = 0; j <data.length;j++){
            short valueAsShort = (short)( (convert[i] << 8)  | (convert[i+1] & 0xff));
            float valueAsFloat = (float)valueAsShort;
            System.out.println(valueAsFloat);
            valueAsFloat = data[j];
            System.out.println(data[j]);
        }can anyone see anythign wrong with the way I am doing this? I cant see anythign wrong but need to make sure its fine before I can continue.
    any advice on this or a better way to do it would be much appreciated.

    ultiron wrote:
    I'm pretty sure they do. The way im doing it is by taking 2 byte values and changing them to a 16 bit float.
    the way the bytes are shift they should only take up 16 bits.It's not that simple.
    First, a float in Java is always 4 bytes. The fact that it has an integer value that can fit into two bytes is irrelevant
    Second, floating point representation is not the same 2s complement that's used for byte, short, int, and long, so you're not just shifting the bits.
    For eample:
    1,  int: 00000000 00000000 00000000 00000001
    1, float: 00111111 10000000 00000000 00000000
    -1,  int: 11111111 11111111 11111111 11111111
    -1, float: 10111111 10000000 00000000 00000000Having said that, you're casting, so your step of going from short to float is correct. It doesn't just shift; it does conversions like the above. The caveats are:
    1) Is your conversion from bytes to short correct? That depends on what those bytes are supposed to be. If they're big-endian representations of 2-byte, 2s-complement numbers, then your code looks correct. You'll still have to test it of course. You'll want to focus on corner cases.
    00 00 --> 0
    00 01 --> 1
    10 00 --> 4096
    7f ff --> 32767
    80 00 --> -32768
    ff ff --> -1
    2) Can float hold all of short's values? I think it can. It obviously can't hold all of int's values, but I think it's precision is sufficient to cover short.
    By the way, is there a reason you're using float instead of double? Unless you're in an extremely memory-constrained environment, there's no reason to use double.

  • Read&write binary float var to file

    Hello everybody.
    Oracle 11G R 2 on Linux.
    My problem.
    I have some millions of records (270.000.000)  with numeric data that can be store in binary float variables. Making the database work with so big table convert the database in a slow and hard to manage, because copys and so. The advantage is that this data only need be read, not modified or add news record.
    So, Im thinking to store in the file system, with UTL_FILE package, one or more binary files and access data through a algorithm to calculate the position of data inside the file. The data can be stored in binary float vars.
    My question.
    How I can add this binary data in binary format to the stream of write and read from the stream of data when I write to disk and when I read from disk.
    Any idea welcome.
    Thanks in advanced & regards everybody.

    I think that you dont understand the problem.
    The problem is easy, I have a table with 270.000.000 records. When you try to do anything with this table the database go slow, for your understand, when you ask a simple and easy query, by example a select count(*) from, it take more than 200 seconds to answer.
    ok, but the data is all numeric that can be stored in binary float var and moreover its position in a sequential file can be calculate.
    So if I make a sequential file, or more than one, where I can save this data I kick this problem to the database.
    And what I´m asking for help is if anybody know a way, using UTL_FILE, to include in the stream to save and read this data from disk (UTL_FILE.put_raw and UTL_FILE.get_raw) in binary float format, nothing more than this I want.
    You are correct that I 'dont understand the problem' because you yourself do not know what the 'problem' is.
    All you said is 'try to do anything with this table the database go slow' but you don't tell us what that 'anything' is. You give only ONE example.
    A COUNT(*) in Oracle could possibly use an index but you don't tell us if you have any indexes. You don't even provide the table DDL so we can see the structure.
    Your description gives the impression that all you have is a table with ONE column defined as BINARY FLOAT and that column is defined as NOT NULL. If that is the case you can create an index and Oracle can use it to get the COUNT(*) results.
    That ONE query is just about the only thing that might be faster with the data in a file. Since each value is four bytes and they can't be null then all you need to know is the length of the file. Then you can divide by four to find out how many entries there are.
    For anything else your 'file' solution will need to read the ENTIRE FILE to do anything other than access values as if the file was a large array of BINARY FLOAT four byte values.
    And for that, as I previously suggested, just forget Oracle and write a simple Java program that uses RandomAccessFile. Then for any given 'array' value just multiply by four, set the FilePointer value to that result and read your 4 bytes.

  • How to read binary file into a 2D float array??

    Hi All,
    I really need help to get this one as I am stuck and can't seem to find any way out of it. I am given a '.dat' file that has float values in it. I want to read this file in java and put it in a 2D float array. The file has basically a matrix of float values. What I want to do is to read this binary file and put all its data into 2D float array (float [] []) so that I can use it in my program. Is there a way to read file like this? I did find a similar matlab code (below) but cant seem to find anything in java and i really want to do this in java only.. I will appreciate ur help in this one.
    thanks very much
    Nitya
    fid = fopen('datafile.dat');
    A = fread(fid,[50 50],'float32');
    fclose(fid);

    I shud have shown the two ways that i Already tried. here they are..
    first one using DataInputStream and then trying to readFloat()
    DataInputStream dis = ....
    Float f = dis.readFloat();This code gives code gives me some random values like this.. (i had a loop)
    5.8758974E-14
    -0.41055492
    1.5724557E-30
    1.06822824E14
    -1.91934371E15
    3.43829601E13
    Other way i tried was this.. which seems right but here i have to convert byte to float and i thnk that code is giving some different results (slightly different float values) not sure why....may be my indexing of the array is wrong to make it a matrix.. or something else...
    is.read(bytes, offset....);
    int cnt = 0;
    int j = 0;
    for (int start = 0; start < offset; start = start + 4) {
      if(j<50){
           myarray[cnt][j] = this.arr2float(bytes, start);
             System.out.println(cnt + "-" + j + " = " + myarray[cnt][j]);
           j++;
    }else{
      if(cnt < 50){
           cnt++;
           j = 0;
      }else{
           break;
    public float arr2float (byte[] arr, int start) {
              int i = 0;
              int len = 4;
              int cnt = 0;
              byte[] tmp = new byte[len];
              for (i = start; i < (start + len); i++) {
                   tmp[cnt] = arr;
                   cnt++;
              int accum = 0;
              i = 0;
              for ( int shiftBy = 0; shiftBy < 32; shiftBy += 8 ) {
                   accum |= ( (long)( tmp[i] & 0xff ) ) << shiftBy;
                   i++;
              return Float.intBitsToFloat(accum);
    Not sure if i am missing some other way to do this...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • GUI building difficulties, nested Frames and other stuff

    I am currently working on a GUI and I am running into some difficulties. I have created a class which extends JFrame
    public class DelFace extends JFrame implements ActionListener, ItemListenerI am instantiating an object of this class from within another object of a different class as follows:
    DelFace DelGUI = new DelFace(this,MastFile);The creation of the object takes place within the listener methods of another object:
    public void actionPerformed(ActionEvent e)
      if(e.getActionCommand().equals("Delete"))
          DelFace DelGUI = new DelFace(this,MastFile);
      }The class that creates the object that makes this call does not contain the main method. Instead the afore mentioned object is created from a class that extends JFrame
    class GUI extends JFrame implements ActionListenerSo the code in it's order of activity is as follows:
    It breaks down hardcore at the beginning
    public class StartProgram {
      private static GUI LauncherGUI;
      private static FileOps MastFile;
      public static void main(String[] args)
      MastFile = new FileOps();
      MastFile.fileStatus();            //Create File object &/or file.
      MastFile.readFile();              //Read file contents if any.
      LauncherGUI = new GUI(StartProgram.MastFile);
    }A GUI object is created, - LauncherGUI = new GUI(StartProgram.MastFile);
    From here the code differentiates somewhat - FileOperations stem from here as do all code related to the complete construction of the General User Interface.
    Specifically my difficulties lie with the GUI, therefore I will present the next peice of code related to the GUI. The following code creates a JFrame and places a whole stack of buttons on it. Included with these buttons are menus. So basically the code creates a menu bar and adds menu items to that bar and so on until a menu similar to that found in any regular program is produced. Also contained on this part of the GUI are the five buttons that are fundemental to the programs operation.
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.EventObject; //Try removing this!!
    class GUI extends JFrame implements ActionListener
      private JButton button1;
      private JButton button2;
      private JButton button3;
      private JButton button4;
      private JButton button5;
      private String Path1;
      private String Path2;
      private String Path3;
      private String Path4;
      private String Path5;
      private FileOps MastFile;
      private DataEntryBox EntryBox;
      private HelpGUI Instruct;
      FrameListener GUIListener = new FrameListener();  //Listener object created.
      GUI(FileOps MastFile)
        this.MastFile = MastFile;          //Make MastFile objects methods available
                                           //to all of LauncherGUI object.
        Toolkit tk = Toolkit.getDefaultToolkit();       //intialize the toolkit.
        Dimension sSize = tk.getScreenSize();           //determine screen size.
        Container c = getContentPane();
        GridBagLayout gridbag2 = new GridBagLayout();    //GridBagLayout object
                                                        //instantiated.
        GridBagConstraints d = new GridBagConstraints();//GridBagConstraints object
                                                        //instantiated.
        c.setLayout(gridbag2);                          //Content pane's layout set
                                                        //to gridbag object.
        d.fill = GridBagConstraints.BOTH;               //Make all components fill
                                                        //their dispaly areas
                                                        //entirely.
        d.insets = new Insets(5,1,5,1);
        JMenuBar menuBar = new JMenuBar();  //Creates Menubar object called menuBar.
        setJMenuBar(menuBar);
        JMenu FMenu = new JMenu("File");    //File Menu object instantiated.
        FMenu.setMnemonic(KeyEvent.VK_F);   //Key that activates File menu...F.
        menuBar.add(FMenu);                 //File Menu added to menuBar object.
        JMenuItem NewItem = new JMenuItem("New");   //Creates New sub-menu object.
        NewItem.setMnemonic(KeyEvent.VK_N);         //Key that activates New sub-
                                                    //menu....N.
        FMenu.add(NewItem);
        NewItem.addActionListener(this);   //ActionListner for NewItem added.
        //Tutorial Note: Steps involved in creating a menu UI are as follows,
        //1). Create an instance of a JMenuBar.
        //2). Create an instance of a JMenu.
        //3). Add items to the JMenu (not to the JMenuBar).
        //Note: It is possible to include the Mnemonic activation key as part of
        //the JMenu or JMenuItem constructor. e.g.: JMenuItem NewItem = new JMenu
        //Item("New",KeyEvent.VK_N);
        JMenuItem DeleteItem = new JMenuItem("Delete");
        DeleteItem.setMnemonic(KeyEvent.VK_D);
        FMenu.add(DeleteItem);
        DeleteItem.addActionListener(this);
        JMenuItem ExitItem = new JMenuItem("Exit",KeyEvent.VK_E); //Mnemonic key
        //included with constructor method here and from now on.
        FMenu.add(ExitItem);
        ExitItem.addActionListener(this);
        JMenu HMenu = new JMenu("Help");
        HMenu.setMnemonic(KeyEvent.VK_H);
        menuBar.add(HMenu);
        JMenuItem InstructItem = new JMenuItem("Instructions",KeyEvent.VK_I);
        HMenu.add(InstructItem);
        InstructItem.addActionListener(this);
        JMenuItem AboutItem = new JMenuItem("About",KeyEvent.VK_A);
        HMenu.add(AboutItem);
        AboutItem.addActionListener(this);
        button1 = new JButton();
    /* The following if statments block first checks to see if the value held in the
    String array is equals to null (note: this only occurs when the program is first
    started and no data has been written to file). If the array is null then the
    buttons text is set to "". If the array value is not null (meaning that the file
    already holds data) then the value of the array is checked. If the value equals
    the String "null" then button text is set to "", otherwise button text is set to
    the relevant array value (a user defined shortcut name). Also the value of each
    buttons actionCommand is set to this string value. */
        if(MastFile.getFDArray(0) == null)
          button1.setText("");
          button1.setActionCommand("Link1");
        else
        if(MastFile.getFDArray(0) != null)
          if(MastFile.getFDArray(0).equals("null"))
            button1.setText("");
            button1.setActionCommand("Link1");
          else
            button1.setText(MastFile.getFDArray(0));
            button1.setActionCommand(MastFile.getFDArray(0));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 0;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button1, d);
        c.add(button1);
        button1.addActionListener(this);
        button2 = new JButton();
        if(MastFile.getFDArray(2) == null) //If the file contains no contents then..
          button2.setText("");
          button2.setActionCommand("Link2");
        else
        if(MastFile.getFDArray(2) != null)
          if(MastFile.getFDArray(2).equals("null"))//If the file contains the string
          {                                        //"null" then do as above.
            button2.setText("");
            button2.setActionCommand("Link2");
          else  //Set both button text and actionCommand to relevant shortcut name.
            button2.setText(MastFile.getFDArray(2));
            button2.setActionCommand(MastFile.getFDArray(2));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 1;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button2, d);
        c.add(button2);
        button2.addActionListener(this);
        button3 = new JButton();
        if(MastFile.getFDArray(4) == null)
          button3.setText("");
          button3.setActionCommand("Link3");
        else
        if(MastFile.getFDArray(4) != null)
          if(MastFile.getFDArray(4).equals("null"))
            button3.setText("");
            button3.setActionCommand("Link3");
          else
            button3.setText(MastFile.getFDArray(4));
            button3.setActionCommand(MastFile.getFDArray(4));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 2;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button3, d);
        c.add(button3);
        button3.addActionListener(this);
        button4 = new JButton();
        if(MastFile.getFDArray(6) == null)
          button4.setText("");
          button4.setActionCommand("Link4");
        else
        if(MastFile.getFDArray(6) != null)
          if(MastFile.getFDArray(6).equals("null"))
            button4.setText("");
            button4.setActionCommand("Link4");
          else
            button4.setText(MastFile.getFDArray(6));
            button4.setActionCommand(MastFile.getFDArray(6));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 3;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button4, d);
        c.add(button4);
        button4.addActionListener(this);
        button5 = new JButton();
        if(MastFile.getFDArray(8) == null)
          button5.setText("");
          button5.setActionCommand("Link5");
        else
        if(MastFile.getFDArray(8) != null)
          if(MastFile.getFDArray(8).equals("null"))
            button5.setText("");
            button5.setActionCommand("Link5");
          else
            button5.setText(MastFile.getFDArray(8));
            button5.setActionCommand(MastFile.getFDArray(8));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 4;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button5, d);
        c.add(button5);
        button5.addActionListener(this);
        Path1 = MastFile.getFDArray(1);       //Load Path variables with path
        Path2 = MastFile.getFDArray(3);       //details from String Array in
        Path3 = MastFile.getFDArray(5);       //MastFile object of FileOps class.
        Path4 = MastFile.getFDArray(7);       //Effectively loading these variables
        Path5 = MastFile.getFDArray(9);       //with file data.
        this.addWindowListener(GUIListener);  //Listener registered with Frame.
        setLocation(sSize.width*1/2,sSize.height*1/20);
        setSize(sSize.width*1/2,sSize.height*1/7);
        setTitle("Java QuickLaunch Toolbar");
        setVisible(true);
      /* The following methods return the ActionCommand and Text Label
         String values of the buttons */
      public String getButton1Command()
        return button1.getActionCommand();
      public String getButton2Command()
        return button2.getActionCommand();
      public String getButton3Command()
        return button3.getActionCommand();
      public String getButton4Command()
        return button4.getActionCommand();
      public String getButton5Command()
        return button5.getActionCommand();
      public String getBt1Text()
        return button1.getText();
      public String getBt2Text()
        return button2.getText();
      public String getBt3Text()
        return button3.getText();
      public String getBt4Text()
        return button4.getText();
      public String getBt5Text()
        return button5.getText();
      /* The following methods set the Path, Button and ActionCommand String values. */
      public void setPath1(String setPath)
        Path1 = setPath;
      public void setPath2(String setPath)
        Path2 = setPath;
      public void setPath3(String setPath)
        Path3 = setPath;
      public void setPath4(String setPath)
        Path4 = setPath;
      public void setPath5(String setPath)
        Path5 = setPath;
      public void setButton1(String setButton)
        button1.setText(setButton);
      public void setButton2(String setButton)
        button2.setText(setButton);
      public void setButton3(String setButton)
        button3.setText(setButton);
      public void setButton4(String setButton)
        button4.setText(setButton);
      public void setButton5(String setButton)
        button5.setText(setButton);
      public void setBt1Action(String setAct)
        button1.setActionCommand(setAct);
      public void setBt2Action(String setAct)
        button2.setActionCommand(setAct);
      public void setBt3Action(String setAct)
        button3.setActionCommand(setAct);
      public void setBt4Action(String setAct)
        button4.setActionCommand(setAct);
      public void setBt5Action(String setAct)
        button5.setActionCommand(setAct);
      /* actionPerformed methods */
      public void actionPerformed(ActionEvent e)
        if(e.getActionCommand().equals("New"))
          //Create a data entry box.
          EntryBox = new DataEntryBox(this,MastFile);
        else
        if(e.getActionCommand().equals("Delete"))//Example part of interest
          DelFace DelGUI = new DelFace(this,MastFile);   /// -------- ////
        else
        if(e.getActionCommand().equals("Exit"))
          System.exit(0);
        else
        if(e.getActionCommand().equals("Instructions"))
          Instruct = new HelpGUI();
        else
        if(e.getActionCommand().equals("About"))
          JOptionPane.showMessageDialog(this,"Java QuickLaunch Toolbar created by David "+
                                        "Dartnell.","Programming Credits",1);
        else
          if(e.getActionCommand().equals(button1.getActionCommand())) //Determine source of event.
          if(Path1 == null)                        //If Path var is a null reference
            EntryBox = new DataEntryBox(this,MastFile);//create a data entry box.
          else
          if(Path1 != null)                        //If not a null reference then...
            if(Path1.equals("null"))               //Determine if string is "null".
              EntryBox = new DataEntryBox(this,MastFile);
            else        //If both the reference and the String are not null then run
            {           //the relevant command/program.
              try
                Runtime.getRuntime().exec(new String[]{Path1});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button2.getActionCommand()))
          if(Path2 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path2 != null)
            if(Path2.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path2});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button3.getActionCommand()))
          if(Path3 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path3 != null)
            if(Path3.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path3});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button4.getActionCommand()))
          if(Path4 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path4 != null)
            if(Path4.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path4});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button5.getActionCommand()))
          if(Path5 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path5 != null)
            if(Path5.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path5});
              catch(IOException run){}
    Something to consider concerning actionListeners:
    It must be remembered that String values are in fact objects and as such
    they require the equals() method unlike their cousins the primitive data
    types (int, float, boolean, byte, short, long and double) which require
    the == operator.
    */A comment is placed next to the line of code that is of interest to my problem (///-------////).
    When a button is pressed in the menu section that reads "Delete" then an actionCommand event is fired and the program responds by creating a second general user interface.
    When DelFace is instantiated in the form of the object called DelGUI I am once again creating an object which extends JFrame. I now have two objects of type JFrame on the screen at once, and I conveniently position one over the top of the other, so to the general user the programs appearance has changed in only very specified ways (i.e.: I have decided to increase the GUI's dimensions in the area of height only and not width). The code that constitutes class DelFace is as follows:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class DelFace extends JFrame implements ActionListener, ItemListener
      private GUI TkBar;        //GUI object.
      private FileOps Fops;     //File Operations object.
      private JCheckBox ckbox1; //Delete shortcut 1.
      private JCheckBox ckbox2; //Delete shortcut 2.
      private JCheckBox ckbox3; //Delete shortcut 3.
      private JCheckBox ckbox4; //Delete shortcut 4.
      private JCheckBox ckbox5; //Delete shortcut 5.
      private JButton OkBtn;    //OK button.
      private JButton CnBtn;    //Cancel button.
      private JOptionPane confirm;
      private boolean short1 = false;  //Boolean variables indicate whether to
      private boolean short2 = false;  //delete a shortcut entry. True = delete.
      private boolean short3 = false;
      private boolean short4 = false;
      private boolean short5 = false;
      DelFace(GUI TkBar, FileOps Fops)
        this.TkBar = TkBar;
        this.Fops = Fops;
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension sSize = tk.getScreenSize();
        Container dcon = getContentPane();
        GridBagLayout gb = new GridBagLayout();
        GridBagConstraints bagcon = new GridBagConstraints();
        dcon.setLayout(gb);
        bagcon.fill = GridBagConstraints.BOTH;
        bagcon.gridwidth = GridBagConstraints.REMAINDER;
        JLabel TLabel = new JLabel("Delete Wizard",JLabel.CENTER);
        TLabel.setFont(new Font("Tahoma",Font.BOLD+Font.ITALIC,32));
        bagcon.gridx = 0;
        bagcon.gridy = 0;
        bagcon.weightx = 1.0;      //Take up all the 'x room' in this row.
        bagcon.weighty = 0.5;      //Take up all the 'y room' in this column.
        /* The weightx and weighty values are required otherwise all components will
           gravitate toward the center of screen. */
        gb.setConstraints(TLabel,bagcon);
        dcon.add(TLabel);
        JTextArea TxArea = new JTextArea("Tick the box(s) of the shortcut(s)"+
                               " that you would like to delete and"+
                               " press the Delete button. Alternatively"+
                               " press the Cancel button to exit.");
        TxArea.setLineWrap(true);
        TxArea.setWrapStyleWord(true);
        TxArea.setEditable(false);
        TxArea.setFont(new Font("Times New Roman",Font.PLAIN,15));
        TxArea.setBackground(this.getBackground());
        bagcon.gridx = 0;
        bagcon.gridy = 1;
        gb.setConstraints(TxArea,bagcon);
        dcon.add(TxArea);
        bagcon.gridwidth = 1;
        JPanel Nopan1 = new JPanel();
        bagcon.gridx = 0;
        bagcon.gridy = 2;
        gb.setConstraints(Nopan1,bagcon);
        dcon.add(Nopan1);
        ckbox1 = new JCheckBox(TkBar.getBt1Text());
        bagcon.gridx = 1;
        bagcon.gridy = 2;
        gb.setConstraints(ckbox1,bagcon);
        dcon.add(ckbox1);
        ckbox1.addItemListener(this);
        ckbox2 = new JCheckBox(TkBar.getBt2Text());
        bagcon.gridy = 3;
        gb.setConstraints(ckbox2,bagcon);
        dcon.add(ckbox2);
        ckbox2.addItemListener(this);
        ckbox3 = new JCheckBox(TkBar.getBt3Text());
        bagcon.gridy = 4;
        gb.setConstraints(ckbox3,bagcon);
        dcon.add(ckbox3);
        ckbox3.addItemListener(this);
        ckbox4 = new JCheckBox(TkBar.getBt4Text());
        bagcon.gridy = 5;
        gb.setConstraints(ckbox4,bagcon);
        dcon.add(ckbox4);
        ckbox4.addItemListener(this);
        ckbox5 = new JCheckBox(TkBar.getBt5Text());
        bagcon.gridy = 6;
        gb.setConstraints(ckbox5,bagcon);
        dcon.add(ckbox5);
        ckbox5.addItemListener(this);
        JPanel Nopan2 = new JPanel();
        bagcon.gridx = 1;
        bagcon.gridy = 7;
        gb.setConstraints(Nopan2,bagcon);
        dcon.add(Nopan2);
        OkBtn = new JButton("OK");
        OkBtn.addActionListener(this);
        bagcon.gridx = 1;
        bagcon.gridy = 8;
        gb.setConstraints(OkBtn,bagcon);
        dcon.add(OkBtn);
        OkBtn.addActionListener(this);
        CnBtn = new JButton("Cancel");
        CnBtn.addActionListener(this);
        bagcon.gridx = 2;
        bagcon.gridy = 8;
        gb.setConstraints(CnBtn,bagcon);
        dcon.add(CnBtn);
        CnBtn.addActionListener(this);
        JPanel Nopan3 = new JPanel();
        bagcon.gridx = 3;
        bagcon.gridy = 8;
        gb.setConstraints(Nopan3,bagcon);
        dcon.add(Nopan3);
        JPanel Nopan4 = new JPanel();
        bagcon.gridx = 0;
        bagcon.gridy = 9;
        gb.setConstraints(Nopan4,bagcon);
        dcon.add(Nopan4);
        setLocation(sSize.width*1/2,sSize.height*1/20);
        setSize(sSize.width*1/2,sSize.height*4/5);
        setTitle("Java QuickLaunch Toolbar");
        setResizable(false);
        setVisible(true);
      public void actionPerformed(ActionEvent e)
      { /*--- Code of INTEREST begins here!!!!!! -------
        if(e.getActionCommand().equals("OK"))   
          if(short1 || short2 || short3 || short4 || short5)
            //confirm = new JOptionPane();
            int n = confirm.showConfirmDialog(this,
                 "Do you really want to delete?","Delete Confirmation",
                 JOptionPane.YES_NO_OPTION);
            if(n == confirm.YES_OPTION)  //Works Fine!
              while(short1 || short2 || short3 || short4 || short5)
                if(short1)
                  TkBar.setBt1Action("Link1");
                  TkBar.setButton1("");
                  TkBar.setPath1("null");
                  Fops.setFDArray(0,"null");
                  Fops.setFDArray(1,"null");
                  short1 = false;
                else
                if(short2)
                  TkBar.setBt2Action("Link2");
                  TkBar.setButton2("");
                  TkBar.setPath2("null");
                  Fops.setFDArray(2,"null");
                  Fops.setFDArray(3,"null");
                  short2 = false;
                else
                if(short3)
                  TkBar.setBt3Action("Link3");
                  TkBar.setButton3("");
                  TkBar.setPath3("null");
                  Fops.setFDArray(4,"null");
                  Fops.setFDArray(5,"null");
                  short3 = false;
                else
                if(short4)
                  TkBar.setBt4Action("Link4");
                  TkBar.setButton4("");
                  TkBar.setPath4("null");
                  Fops.setFDArray(6,"null");
                  Fops.setFDArray(7,"null");
                  short4 = false;
                else
                if(short5)
                  TkBar.setBt5Action("Link5");
                  TkBar.setButton5("");
                  TkBar.setPath5("null");
                  Fops.setFDArray(8,"null");
                  Fops.setFDArray(9,"null");
                  short5 = false;
              Fops.destroyFile();   //Destroy the old (outdated) file.
              Fops.fileStatus();    //Create a new file.
              Fops.writeFile();     //Write updated data to new file.
              setVisible(false);
            if(n == confirm.NO_OPTION)  //** Does not work ***
              System.out.println("No Option is being heard");
              //Listeners are working.
              //confirm.setVisible(false);
            if(n == confirm.CLOSED_OPTION) //** Does not work ***
              System.out.println("Closed Option is being heard");
              //Listeners are working.
              //confirm.setVisible(false);
        --- Code of interest ENDS here --- */
        else
        if(e.getActionCommand().equals("Cancel"))
          setVisible(false); 
      public void itemStateChanged(ItemEvent f)
        int state = f.getStateChange();
        if(state == ItemEvent.SELECTED)   //If a checkbox has been selected.
          if(f.getItem() == ckbox1)
            short1 = true;
          else
          if(f.getItem() == ckbox2)
            short2 = true;
          else
          if(f.getItem() == ckbox3)
            short3 = true;
          else
          if(f.getItem() == ckbox4)
            short4 = true;
          else
          if(f.getItem() == ckbox5)
            short5 = true;
        if(state == ItemEvent.DESELECTED)  //If a checkbox has been deselected.
          if(f.getItem() == ckbox1)
            short1 = false;
          else
          if(f.getItem() == ckbox2)
            short2 = false;
          else
          if(f.getItem() == ckbox3)
            short3 = false;
          else
          if(f.getItem() == ckbox4)
            short4 = false;
          else
          if(f.getItem() == ckbox5)
            short5 = false;
    }The code that is of interest to my current programming challenge is marked in the above code block like this:
    //*** Code of INTEREST begins here!!!!!! ********** //
    This is where my programming twilight behaviour begins to kick in. From the DelGUI object I now listen to a button event, this event when triggered causes a JOptionPane.showConfirmDialog(), as can be seen in the specified code block above. I make the JOptionPane centered over the DelGUI object ("JFrame No.: 2") which is also centered over the LauncherGUI object ("JFrame No.: 1").
    The program begins to behave quite strangely after the creation of the JOptionPane object called confirm. The JOptionPane is presented on screen without any visiual difficulty but it behaves quite strangely when it's buttons are pressed. The JOptionPane contains three event sources, the YES, NO and Close buttons.
    In my program the YES button causes a set of file operations to take place and then sets the "JFrame No.: 2"(DelGUI) invisible. It does this via the method setVisible(false). "JFrame No.: 2" is effectively the JOptionPane's parent component and as soon as it is setVisible(false) the JOptionPane is also cleared from the screen. I believe from my research that this is the JOptionPane's default behaviour, meaning that as soon as a button or event source is activated the JOptionPane will destroy itself.
    The end of the trail is near, thankyou for reading this if you have got this far, and please carry on....
    The Challenge:
    The program does not behave as desired at the two points in the code commented as such: ** Does not work ***
    if(n == confirm.NO_OPTION)
              System.out.println("No Option is being heard");
              //confirm.setVisible(false);
            if(n == confirm.CLOSED_OPTION)
              System.out.println("Closed Option is being heard");
              //confirm.setVisible(false);
            }If the NO_OPTION or the CLOSED_OPTION are pressed then the JOptionPane remains visible. After pressing the JoptionPane's button a second time it will disappear completely. I have tried a number of things in an attempt to work this out. Firstly I have inserted println messages to ensure that the events are being detected. These messages are always displayed whenever either the NO or Close buttons are pressed.
    As these messages are being passed to the Standard Output, twice by the time the JOptionPane has disappeared, I can only assume that the events are being detected.
    In addition to checking the event situation I have attempted to explicity set the JOptionPane invisible, in the form:
    confirm.setVisible(false); The above line of code did not change the situation. Still I need two button clicks for the JOptionPane to display it's default behaviour which is to set itself invisible (or possibly the object is alloted to garbage collection), either way it is no longer on screen. I have also tried this code with no if statements related to NO_OPTION and CLOSE_OPTION. This was done in an attempt to allow the default behaviour to take place. Unfortunately two presses were still required in this situation.
    A forum member mentioned the possibility that two JOptionPanes are being created. I have checked my code and am confident that I have not explicitly created the JOptionPane twice (the code throughout this question should support this).
    Is it possible that two JOptionPanes are being created because of the nature of my code, the fact that there are two JFrames on the screen at once when the JOptionPane is instantiated? I am using the this keyword to specify the parent of the JOptionPan

    Well, I've checked your code and I've seen where is the error.
    In Delface constructor (Delface.java, line 127), you've got this block of code :
    1. OkBtn = new JButton("OK");
    2. OkBtn.addActionListener(this);
    3. bagcon.gridx = 1;
    4. bagcon.gridy = 8;
    5. gb.setConstraints(OkBtn,bagcon);
    6. dcon.add(OkBtn);
    7. OkBtn.addActionListener(this);
    Have a deep look at lines 2 and 7 : you're registering twice an actionListener on this button. Then you're receiving twice the event and it shows two JOptionPanes. In fact, you've also the problem with the 'ok' option, but you don't see it, because the 'n' variable in your event handler is global to your class, then it's shared between the two calls to the event handlers.

  • JDBC Mysql Resultset too large!

    Hello everybody,
    I'm currently building a large database retrieval system(JAVA and mysql). Everything works fine, but I have a big problem. The returning resultset is way higher then it should be!!
    The table has the following structure:
    Probe_set_id unsigned mediumint(6)
    Expressionvalue float(5,1)
    Dataset unsigned tinyint(2)
    I'm trying to retrieve a dataset with 6.5 million rows with the following query.
    Select Probe_Set_ID, Expressionvalue from Test5 where dataset=1
    This results in JAVA taking around 500 megabyte retrieving the Resultset!!! If my calculations are right it should take around the following:
    Float 4 bytes * 6500000 = 26000000 bytes
    unsigned mediumint = long 8 bytes * 6500000 = 52000000 bytes
    That would be 78000000 bytes, which is around 75 megabyte and not 500 megabyte!!!!!
    Code sample:
                   String dataBaseName = "testDB";
                   String dataBaseUser = "java";
                   String dataBasePass = "clustering";
                   String url = "jdbc:mysql://localhost/" + dataBaseName;
                   Class.forName ("org.gjt.mm.mysql.Driver").newInstance ();
                   Connection conn = DriverManager.getConnection (url, dataBaseUser, dataBasePass);
                   conn.setReadOnly(true);
                   Statement s = conn.createStatement();
                   s.execute("Select Probe_Set_ID, Expressionvalue from Test5 where dataset=1");
                   ResultSet rs = s.getResultSet();
    This results in a giant resultset and I can't see the answer. I hope someone can help me. I'm using the newest JDBC driver of mysql!

    Yes the JAVA application really takes up this amount! It is really akward. The DB doesn't take a real big amount of memory because of the buffer sizes I've set. I execute the java application as follow:
    ./java -server -XX:MaxHeapFreeRatio=5 -XX:MinHeapFreeRatio=20 -Xmx1512M dbTest
    I'm really trying to keep the heap small because the JAVA application ( a gene expression processing application/server) takes big amounts of memmory when downloading data from the mysql database and the server is accesible by multiple users parallel. Though I'm still testing alone, so the memmory abuse is not a cause by other users.

  • Mapping Java Types to XML Types

    Hi, I have a small doubt in web services,
    1)  how a java data type can match with xml data type in wsdl,
    2)  how and where the java program can find the matching java
        data type to xml data type and vice versa
    3)  whether any mechanism is available for this data conversion?
    4)  where can i find that one?
    Please advice me
    Regards
    Marimuthu.N

    Hi Marimuthu.N,
    My answers for your question, Kindly let me know if you need some more inputs.
    +1) how a java data type can match with xml data type in wsdl,+
    In SOAP 1.1 you have the following data types which is in XSD(XML Schema Definition), the same data type is also available in Java. For example (string, normalizedstring in xml is available as java.lang.String)
    The complete list can be found in the table below.
    XSD to Java Mapping.
    XSD Type--------------------------------Java Type
    base64Binary----------------------------byte[]
    hexBinary---------------------------------byte[]
    boolean------------------------------------Boolean
    byte-----------------------------------------Byte
    dateTime----------------------------------java.util.Calendar
    date-----------------------------------------java.util.Calendar
    time-----------------------------------------java.util.Calendar
    decimal------------------------------------java.math.BigDecimal
    double-------------------------------------Double
    float-----------------------------------------Float
    hexBinary---------------------------------byte[]
    int--------------------------------------------Int
    unsignedShort---------------------------Int
    integer--------------------------------------java.math.BigInteger
    long------------------------------------------Long
    unsignedInt-------------------------------Long
    QName-------------------------------------javax.xml.namespace.QName
    short----------------------------------------Short
    unsignedByte---------------------------Short
    string---------------------------------------java.lang.String
    anySimpleType-------------------------java.lang.String
    +2) how and where the java program can find the matching java+
    data type to xml data type and vice versa
    Here is my WSDL which has a method getHello --> Pass Input as String --> Get Response as String.
    <?xml version="1.0" encoding="UTF-8"?>
    <wsdl:definitions targetNamespace="http://zackria.googlepages.com" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://zackria.googlepages.com" xmlns:intf="http://zackria.googlepages.com" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <!--WSDL created by Apache Axis version: 1.4
    Built on Apr 22, 2006 (06:55:48 PDT)-->
    <wsdl:types>
      <schema elementFormDefault="qualified" targetNamespace="http://zackria.googlepages.com" xmlns="http://www.w3.org/2001/XMLSchema">
       <element name="getHello">
        <complexType>
         <sequence>
          <element name="s" type="xsd:string"/>
         </sequence>
        </complexType>
       </element>
       <element name="getHelloResponse">
        <complexType>
         <sequence>
          <element name="getHelloReturn" type="xsd:string"/>
         </sequence>
        </complexType>
       </element>
      </schema>
    </wsdl:types>
       <wsdl:message name="getHelloResponse">
          <wsdl:part element="impl:getHelloResponse" name="parameters"/>
       </wsdl:message>
       <wsdl:message name="getHelloRequest">
          <wsdl:part element="impl:getHello" name="parameters"/>
       </wsdl:message>
       <wsdl:portType name="Test">
          <wsdl:operation name="getHello">
             <wsdl:input message="impl:getHelloRequest" name="getHelloRequest"/>
             <wsdl:output message="impl:getHelloResponse" name="getHelloResponse"/>
          </wsdl:operation>
       </wsdl:portType>
       <wsdl:binding name="TestSoapBinding" type="impl:Test">
          <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
          <wsdl:operation name="getHello">
             <wsdlsoap:operation soapAction=""/>
             <wsdl:input name="getHelloRequest">
                <wsdlsoap:body use="literal"/>
             </wsdl:input>
             <wsdl:output name="getHelloResponse">
                <wsdlsoap:body use="literal"/>
             </wsdl:output>
          </wsdl:operation>
       </wsdl:binding>
       <wsdl:service name="TestService">
          <wsdl:port binding="impl:TestSoapBinding" name="Test">
             <wsdlsoap:address location="http://localhost:8080/TestWebService/services/Test"/>
          </wsdl:port>
       </wsdl:service>
    </wsdl:definitions>I use apache axis for the client side code. I also suggest to start using this to get quickly into SOA(Service Oriented Architecture)
    package com.googlepages.zackria;
    import org.apache.axis.client.Call;
    import org.apache.axis.client.Service;
    import javax.xml.namespace.QName;
    * TestClient for Webservice
    * @author $author$Mohammed Zackria
    * @version $Revision$1.00
    public class TestClient {
         * main method
         * @param args pass nothing as far now
        public static void main(String[] args) {
            try {
                String endpoint = "http://localhost:8080/TestWebService/services/Test";
                Service service = new Service();
                Call call = (Call) service.createCall();
                call.setTargetEndpointAddress(new java.net.URL(endpoint));
                call.setOperationName(new QName("http://zackria.googlepages.com", "getHello"));
                //String Conversion
                String ret = (String) call.invoke(new Object[] { "Zack" });
                System.out.println("Sent 'Zack', got '" + ret + "'");
            } catch (Exception e) {
                System.err.println(e.toString());
    }+3) whether any mechanism is available for this data conversion?+
    Check the above code which has the following portion
    //String Conversion
    String ret = (String) call.invoke(new Object[] { "Zack" });
    By default APACHE Axis returns Object Array which can be Casted to your WSDL defined data type.
    +4) where can i find that one?+
    [Eclipse Webservice|http://www.eclipse.org/webtools/jst/components/ws/1.5/tutorials/BottomUpWebService/BottomUpWebService.html]
    Hope this helps out, Kindly Let me know if you need some more or if i have not answered your question.
    Regards,
    Zack
    Edited by: zack on Nov 22, 2008 1:47 PM
    Edited by: zack on Nov 22, 2008 1:49 PM

  • How to use MapDepthPointToCameraSpace

    This is a public-service post. There was so little documentation available about MapDepthPointToCameraSpace -- and no code examples available at all, in the SDK Browser or elsewhere -- that I was compelled to reverse-engineer the method, just to figure out
    how to use it, and here is what I discovered.
    Here is the syntax of the method:
    public CameraSpacePoint MapDepthPointToCameraSpace (
    DepthSpacePoint depthPoint,
    UInt16 depth
    The critical thing to understand about this method, and the source of much boondoggling until I figured it out, is that the input is in
    millimeters, while the output is in
    meters.
    Uint16 depth -> This is a depth value, unsigned integer (two bytes wide), in units of
    millimeters.
    DepthSpacePoint depthPoint -> This is a struct containing an [x,y] coordinate. The [x,y] describe a 2D coordinate location on the incoming depth-map from the Kinect, with [0,0] at upper-left corner. This struct contains two properties,
    X and Y, which are signed floats (four bytes wide); however, you should assign only positive integers to these X and Y properties. There is no constructor for this struct, so you must create a DepthSpacePoint in several steps, shown in the code example below.
    CameraSpacePoint -> This is a struct containing an [x,y,z] coordinate. The [x,y,z] describe a 3D coordinate location in the reference space established by the Kinect sensor itself. This struct contains three properties, X and Y and Z,
    which are signed floats (four bytes wide), representing coordinates in physical space, in units of
    meters. Although z will always be positive (a zero value indicates an unknown depth value or error), each of x and y may be positive, zero, or negative. If MapDepthPointToCameraSpace cannot complete its calculation
    successfully -- for example, an object is too close to the sensor -- then any of the [x,y,z] values may be set to +Infinity or to -Infinity. Attempting to use these infinite values will not throw an exception -- instead, you'll find your variables being
    set to MAXINT or -MAXINT and you will be completely confused by the end results. So you must carefully screen for infinite values when using MapDepthPointToCameraSpace.
    Example usage:
    CoordinateMapper m = myKinectSensor.CoordinateMapper;DepthSpacePoint d = new DepthSpacePoint(); // no constructor is availabled.X = 100; // in pixelsd.Y = 200; // in pixelsCameraSpacePoint p = m.MapDepthPointToCameraSpace(     d,     // in pixels 2500); // in millimeters
    The above code queries the coordinate mapper for pixel-coordinate [x,y] = [100,200] in the Kinect depth map, with input depth value of 2500
    millimeters. The output is as follows:
    p.X, p.Y, and p.Z contain the mapped 3D coordinate in the Kinect's reference spatial system, in floating-point
    meters, where:
    X and Y will be positive, zero, or negative if calculation succeeds. They will be plus or minus infinity if a calculation error occurs.
    Z will be positive if the calculation succeeds. It will be zero or plus or minus infinity if a calculation error occurs.
    I hope that this information is helpful to others!
    - ZMK

    This is a public-service post. There was so little documentation available about MapDepthPointToCameraSpace -- and no code examples available at all, in the SDK Browser or elsewhere -- that I was compelled to reverse-engineer the method, just to figure out
    how to use it, and here is what I discovered.
    Here is the syntax of the method:
    public CameraSpacePoint MapDepthPointToCameraSpace (
    DepthSpacePoint depthPoint,
    UInt16 depth
    The critical thing to understand about this method, and the source of much boondoggling until I figured it out, is that the input is in
    millimeters, while the output is in
    meters.
    Uint16 depth -> This is a depth value, unsigned integer (two bytes wide), in units of
    millimeters.
    DepthSpacePoint depthPoint -> This is a struct containing an [x,y] coordinate. The [x,y] describe a 2D coordinate location on the incoming depth-map from the Kinect, with [0,0] at upper-left corner. This struct contains two properties,
    X and Y, which are signed floats (four bytes wide); however, you should assign only positive integers to these X and Y properties. There is no constructor for this struct, so you must create a DepthSpacePoint in several steps, shown in the code example below.
    CameraSpacePoint -> This is a struct containing an [x,y,z] coordinate. The [x,y,z] describe a 3D coordinate location in the reference space established by the Kinect sensor itself. This struct contains three properties, X and Y and Z,
    which are signed floats (four bytes wide), representing coordinates in physical space, in units of
    meters. Although z will always be positive (a zero value indicates an unknown depth value or error), each of x and y may be positive, zero, or negative. If MapDepthPointToCameraSpace cannot complete its calculation
    successfully -- for example, an object is too close to the sensor -- then any of the [x,y,z] values may be set to +Infinity or to -Infinity. Attempting to use these infinite values will not throw an exception -- instead, you'll find your variables being
    set to MAXINT or -MAXINT and you will be completely confused by the end results. So you must carefully screen for infinite values when using MapDepthPointToCameraSpace.
    Example usage:
    CoordinateMapper m = myKinectSensor.CoordinateMapper;DepthSpacePoint d = new DepthSpacePoint(); // no constructor is availabled.X = 100; // in pixelsd.Y = 200; // in pixelsCameraSpacePoint p = m.MapDepthPointToCameraSpace(     d,     // in pixels 2500); // in millimeters
    The above code queries the coordinate mapper for pixel-coordinate [x,y] = [100,200] in the Kinect depth map, with input depth value of 2500
    millimeters. The output is as follows:
    p.X, p.Y, and p.Z contain the mapped 3D coordinate in the Kinect's reference spatial system, in floating-point
    meters, where:
    X and Y will be positive, zero, or negative if calculation succeeds. They will be plus or minus infinity if a calculation error occurs.
    Z will be positive if the calculation succeeds. It will be zero or plus or minus infinity if a calculation error occurs.
    I hope that this information is helpful to others!
    - ZMK

  • TCP communicat​ions via C program with VI on a PC (SGI - Windows)

    I have a pair of simple (more at prototype) client/server C programs on an
    SGI host. On the SGI, they compile and run fine (using separate windows).
    I know what the server is supposed to be sending (C floats) and the client
    is reading the correct values.
    I now want to start my C program server on the SGI host, and use the Simple
    Data Client.vi (in LabVIEW 6.1's examples) to display (in its graph) the
    floating point values that the SGI host is sending.
    So far, I have not had complete success. If I start my SGI server, and
    "point" the example Simple Data Client VI at my server, the LabVIEW client
    gets immediate errors (overflows).
    As an experiment, I tried going the other way. That it, I started up
    the
    Simple Data Server VI on the Windows PC. I then "pointed" my SGI client at
    the server on the PC. It works, ... sort of. I am getting an
    appropriately sized list of numbers displayed on the SGI host, but while
    most look like floating point values, some look like VERY large integers.
    I believe I have a data representation problem. That is, I don't know if I
    should expect to send (server-side) or see (client-side) C programming
    variables of type 4-byte floats, 8 byte doubles, or something else. Also, I
    am not certain how many values I should expect to send/see in each message.
    I think the default for the Simple Data Client/Server programs is 200
    points, but I am not sure what that really means, either.
    Any suggestions would be very much appreciated.
    Mike McCormick
    Michael J. McCormick
    Phone: 520-545-7972
    Fax: 520-794-9400
    Email: [email protected]

    > As an experiment, I tried going the other way. That it, I started up the
    > Simple Data Server VI on the Windows PC. I then "pointed" my SGI client at
    > the server on the PC. It works, ... sort of. I am getting an
    > appropriately sized list of numbers displayed on the SGI host, but while
    > most look like floating point values, some look like VERY large integers.
    >
    > I believe I have a data representation problem. That is, I don't know if I
    > should expect to send (server-side) or see (client-side) C programming
    > variables of type 4-byte floats, 8 byte doubles, or something else. Also, I
    > am not certain how many values I should expect to send/see in each message.
    > I think the default for the Simple Data Client/Server programs is 200
    > points
    , but I am not sure what that really means, either.
    >
    By default, LV converts all of the datatypes to be in big endian form.
    I'm not sure about your SGI, but if it is a little endian machine, then
    that will cause problems. If that is the case, you will want to swap
    the words and bytes of the four byte values.
    To debug this more easily, you might just make sure you send over very
    predictable data such as 0, 1, 2, 3, etc. Lots of times these are
    tested with random data, but that makes it pretty hard to see a pattern
    when the data is wrong.
    Greg McKaskle

  • Primitive type Changing???

    One of my friends sent me this e-mail. Can anyone help??
    ok wood, here's one for you:
    the software i'm writing get's data from one of two processors on a
    satelite. these processors use different #'s of bytes for their
    primitive types.
    bool - 1 byte
    short - 2 bytes
    int - 2 bytes
    long - 4 bytes
    float - 4 bytes.
    so..as you know the jvm uses 4 bytes for an int, 8 for a long. I
    want to be able to have people who are developing sims ontop of my
    framework be able to use a primitiave type, such as an int, and have
    it only be 2 bytes...now i'm pretty sure this isn't possible. You
    can't overload a primitive type in java right? I have some ideas
    here on what to do (create whole new objects, holding byte arrays and
    use java.nio to manaage them), but it just seems like such a hastel.
    i guess i was wondering if you have ever seen this kindof thing
    before and if you had any advice. thanks man.

    In C, primitive types can vary in size, based on the platform being used. In Java, the size of primitives is static. If he wants 16-bit storage, short is the way to go. Well, a char is a couple of bytes, too, but it's unsigned, intended for Unicode characters, and probably not what he's looking for anyway...
    :o)

  • Edit method problem???

    Hi,forgive for all the code but i've asked this question before and people asked for more code.The problem is i get an error in publicationmain saying "undefined varible newpublication" so how do i fix this?and is my edit method goin to work?using the get and set method?can u show me how do do this please?feel free to make any other changes.thanxs a reply would be most heplful
    public class publication
    public int PublicationID;
    public String publicationname;
    public String publisher;
    public String PricePerIssue;
    public String pubstatus;
    public String publicationtype;
    public publication(int NewPublicationID, String Newpublicationname, String Newpublisher, String NewPricePerIssue, String Newpubstatus, String Newpublicationtype)
    PublicationID = NewPublicationID;
    publicationname = Newpublicationname;
    publisher = Newpublisher;
    PricePerIssue = NewPricePerIssue;
    pubstatus = Newpubstatus;
    publicationtype = Newpublicationtype;
    public String toString ()
    String pubreport = "---------------------------Publication-Information-----------------------------";
    pubreport += "Publication ID:" PublicationID"/n";
    pubreport += " Publication Title:" publicationname"/n";
    pubreport += " publisher: " publisher"/n";
    pubreport += " price Per Issue: " PricePerIssue"/n";
    pubreport += " publication Status: " pubstatus"/n";
    pubreport += " publication Type: " publicationtype"/n";
    return pubreport;
    public void SetPublicationID(int PubID)
    PublicationID = PubID;
    public int GetPublicationID()
    return PublicationID;
    public void Setpublicationname(String pubname)
    publicationname = pubname;
    public String Getpublicationname()
    return publicationname;
    public void Setpublisher(String Pub)
    publisher = Pub;
    public String Getpublisher()
    return publisher;
    public void SetPricePerIssue(String PPI)
    PricePerIssue = PPI;
    public String GetPricePerIssue()
    return PricePerIssue;
    public void Setpubstatus(String Status)
    pubstatus = Status;
    public String Getpubstatus()
    return pubstatus;
    public void Setpublicationtype(String Pubtype)
    publicationtype = Pubtype;
    public String Getpublicationtype()
    return publicationtype;
    import java.util.*;
    import publication;
    public class PublicationContainer
    LinkedList PubList;
    public PublicationContainer()
    PubList = new LinkedList();
    public int add (publication newpublication)
    PubList.addLast(newpublication);
    return PubList.size();
    private class PubNode
    public publication pubrecord;
    public PubNode next;
    public PubNode (publication thepublicationrecord)
    publication p = thepublicationrecord;
    next = null;
    public String toString()
    return PubList.toString();
    public void remove(int PubID)
    PubList.remove(PubID);
    public publication get(int PubID)
    return (publication)PubList.get(PubID);
    public void set(int PubID,publication newpublication)
    PubList.set(PubID, newpublication);
    import cs1.Keyboard;
    import publication;
    import java.util.*;
    public class publicationmain
    public static void main(String args[])
    PublicationContainer pubdatabase = new PublicationContainer();
    int userchoice;
    boolean flag = false;
    while (flag == false)
    System.out.println("------------------------------------Publications--------------------------------");
    System.out.println();
    System.out.println("please Make a Selection");
    System.out.println();
    System.out.println("1 to add publication");
    System.out.println("2 to delete publication");
    System.out.println("0 to quit");
    System.out.println("3 to View all publications");
    System.out.println("4 to Edit a publication");
    System.out.println("5 to select view of publication");
    System.out.println("6 to produce daily summary");
    System.out.println();
    userchoice = Keyboard.readInt();
    switch (userchoice)     
    case 1:
    String PubName;
    String PricePerIssue;
    String Publisher;
    String Pubstatus;
    String Pubtype;
    int PubID;
    System.out.println ("Enter Publication ID:");
    PubID = Keyboard.readInt();
    System.out.println("Enter Publication Name:");
    PubName = Keyboard.readString();
    System.out.println("Enter Publisher Name");
    Publisher = Keyboard.readString();
    System.out.println("Enter Price per Issue:");
    PricePerIssue = Keyboard.readString();
    System.out.println("Enter Publication status");
    Pubstatus = Keyboard.readString();
    System.out.println("Enter Publication type:");
    Pubtype = Keyboard.readString();
    pubdatabase.add (new publication(PubID, PubName, Publisher, PricePerIssue, Pubstatus, Pubtype));
    break;
    case 0:
    flag = true;
    case 2:
    System.out.println ("Enter Publication ID:");
    PubID = Keyboard.readInt();
    pubdatabase.remove (PubID);
    System.out.println ("publication: "+(PubID)+" removed");
    System.out.println();
    break;
    case 3:
    System.out.println (pubdatabase);
    break;
    case 4:
    System.out.println ("Enter Publication to be edited by Publication ID: ");
    PubID = Keyboard.readInt();
    pubdatabase.get(PubID);
    pubdatabase.set(PubID, newpublication);
    default:
    System.out.println("Incorrect Entry");
    }

    Whoops! Anyone spot the mistake?
    I (blush) forgot to re-instate the serial key for the publications after reading them in from disk.
    Works now ;)
    import javax.swing.JComponent;
    import javax.swing.JList;
    import javax.swing.DefaultListModel;
    import javax.swing.JPanel;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.JScrollPane;
    import javax.swing.JLabel;
    import javax.swing.JComboBox;
    import javax.swing.JTextField;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.Dimension;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.Serializable;
    class Publication
         implements Serializable
         private static final String sFileName= "Publications.ser";
         public static final byte UNKNOWN=     0;
         public static final byte HARDBACK=    1;
         public static final byte PAPERBACK=   2;
         public static final byte AUDIO=       3;
         public static final byte BRAIL=       4;
         public static final byte LARGE_PRINT= 5;
         public static final byte INSTOCK=      1;
         public static final byte BACK_ORDER=   2;
         public static final byte OUT_OF_PRINT= 3;
         private static final String[] sTypeNames=
              { "Unknown", "Hardback", "Paperback", "Audio", "Brail", "Large Print" };
         private static final String[] sStatusNames=
              { "Unknown", "In Stock", "Back Order", "Out of Print" };
         private int mId;
         private String mTitle;
         private String mAuthor;
         private String mPublisher;
         private float mPrice;
         private byte mStatus;
         private byte mType;
         private static Object sIdLock= new Object();
         static int sId;
         public Publication(
              String title, String author, String publisher,
              float price, byte status, byte type)
              setTitle(title);
              setPublisher(publisher);
              setAuthor(author);
              setPrice(price);
              setStatus(status);
              setType(type);
              synchronized (sIdLock) {
                   mId= ++sId;
         public int getId() { return mId; }
         public void setTitle(String title) { mTitle= title; }
         public String getTitle() { return mTitle; }
         public void setAuthor(String author) { mAuthor= author; }
         public String getAuthor() { return mAuthor; }
         public void setPublisher(String publisher) { mPublisher= publisher; }
         public String getPublisher() { return mPublisher; }
         public void setPrice(float price) { mPrice= price; }
         public float getPrice() { return mPrice; }
         public void setStatus(byte status)
              if (status >= INSTOCK && status <= OUT_OF_PRINT)
                   mStatus= status;
              else
                   mStatus= UNKNOWN;
         public byte getStatus() { return mStatus; }
         public String getStatusName() { return sStatusNames[mStatus]; }
         public void setType(byte type)
              if (type >= HARDBACK && type <= LARGE_PRINT)
                   mType= type;
              else
                   mType= UNKNOWN;
         public byte getType() { return mType; }
         public String getTypeName() { return sTypeNames[mType]; }
         public String toString ()
              return
                   " id= " +getId() +
                   ", title= " +getTitle() +
                   ", author= " +getAuthor() +
                   ", publisher= " +getPublisher() +
                   ", price= " +getPrice() +
                   ", status= " +getStatus() +
                   " (" +getStatusName() +")" +
                   ", type= " +getType() +
                   " (" +getTypeName() +")";
         private static void addPublication(DefaultListModel listModel) {
              editPublication(listModel, null);
         private static void editPublication(
              DefaultListModel listModel, Publication publication)
              JPanel panel= new JPanel(new BorderLayout());
              JPanel titlePanel= new JPanel(new GridLayout(0,1));
              JPanel fieldPanel= new JPanel(new GridLayout(0,1));
              JTextField fTitle= new JTextField(20);
              JTextField fAuthor= new JTextField();
              JTextField fPublisher= new JTextField();
              JTextField fPrice= new JTextField();
              JComboBox cbStatus= new JComboBox(sStatusNames);
              JComboBox cbType= new JComboBox(sTypeNames);
              fieldPanel.add(fTitle);
              fieldPanel.add(fAuthor);
              fieldPanel.add(fPublisher);
              fieldPanel.add(fPrice);
              fieldPanel.add(cbStatus);
              fieldPanel.add(cbType);
              titlePanel.add(new JLabel("Title:"));
              titlePanel.add(new JLabel("Author:"));
              titlePanel.add(new JLabel("Publisher: "));
              titlePanel.add(new JLabel("Price:"));
              titlePanel.add(new JLabel("Status:"));
              titlePanel.add(new JLabel("Type:"));
              panel.add(titlePanel, BorderLayout.WEST);
              panel.add(fieldPanel, BorderLayout.EAST);
              if (publication != null) {
                   fTitle.setText(publication.getTitle());
                   fTitle.setEditable(false);
                   fAuthor.setText(publication.getAuthor());
                   fPublisher.setText(publication.getPublisher());
                   fPrice.setText("" +publication.getPrice());
                   cbStatus.setSelectedIndex((int) publication.getStatus());
                   cbType.setSelectedIndex((int) publication.getType());
              int option= JOptionPane.showOptionDialog(
                   null, panel, "New Publication",
                   JOptionPane.OK_CANCEL_OPTION,
                   JOptionPane.PLAIN_MESSAGE,
                   null, null, null
              if (option != JOptionPane.OK_OPTION)
                   return;
              String title=
                   fTitle.getText().length() < 1 ? "Unknown" : fTitle.getText();
              String author=
                   fAuthor.getText().length() < 1 ? "Unknown" : fAuthor.getText();
              String publisher=
                   fPublisher.getText().length() < 1 ? "Unknown" : fPublisher.getText();
              float price= 0.0f;
              try { price= Float.parseFloat(fPrice.getText()); }
              catch (NumberFormatException nfe) { }
              byte status= (byte) cbStatus.getSelectedIndex();
              byte type= (byte) cbType.getSelectedIndex();
              if (publication != null) {
                   publication.setAuthor(author);
                   publication.setPublisher(publisher);
                   publication.setPrice(price);
                   publication.setStatus(status);
                   publication.setType(type);
              else {
                   listModel.addElement(
                        new Publication(title, author, publisher, price, status, type));
         private static void deletePublications(JList list, DefaultListModel listModel)
              if (list.getSelectedIndex() >= 0) {
                   Object[] values= list.getSelectedValues();
                   for (int i= 0; i< values.length; i++)
                        listModel.removeElement(values);
         private static DefaultListModel getListModel()
              DefaultListModel listModel;
              try {
                   ObjectInputStream is=
                        new ObjectInputStream(new FileInputStream(sFileName));
                   listModel= (DefaultListModel) is.readObject();
                   is.close();
                   if (listModel.getSize() > 0) {
                        Publication.sId=
                             ((Publication)
                                  listModel.get(listModel.getSize() -1)).getId();
              catch (Exception e) {
                   JOptionPane.showMessageDialog(
                        null, "Could not find saved Publications, creating new list.",
                        "Error", JOptionPane.ERROR_MESSAGE);
                   listModel= new DefaultListModel();
                   // add a known book to the list (I'm pretty sure this one exists ;)
                   listModel.addElement(
                        new Publication("The Bible", "Various", "God", 12.95f,
                             Publication.INSTOCK, Publication.HARDBACK));
              // add a shutdown hook to save the list model to disk when we exit
              final DefaultListModel model= listModel;
              Runtime.getRuntime().addShutdownHook(new Thread() {
                   public void run() {
                        saveListModel(model);
              return listModel;
         private static void saveListModel(DefaultListModel listModel)
              try {
                   ObjectOutputStream os=
                        new ObjectOutputStream(new FileOutputStream(sFileName));
                   os.writeObject(listModel);
                   os.close();
              catch (IOException ioe) {
                   System.err.println("Failed to save Publications!");
                   ioe.printStackTrace();
         public static void main(String args[])
              // store all the publications in a list model which drives the JList
              // the user will see - we save it on exit, so see if there's one on disk.
              final DefaultListModel listModel= getListModel();
              final JList list= new JList(listModel);
              // two panels, the main one for the dialog and one for buttons
              JPanel panel= new JPanel(new BorderLayout());
              JPanel btnPanel= new JPanel(new GridLayout(1,0));
              // an add button, when pressed brings up a dialog where the user can
              // enter details of a new publication
              JButton btnAdd= new JButton("Add");
              btnAdd.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        addPublication(listModel);
              btnPanel.add(btnAdd);
              // a delete button, when pressed it will delete all the selected list
              // items (if any) and then disable itself
              final JButton btnDelete= new JButton("Delete");
              btnDelete.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        deletePublications(list, listModel);
              btnDelete.setEnabled(false);
              btnPanel.add(btnDelete);
              // hook into the list selection model so we can de-activate the delete
              // button if no list items are selected.
              list.getSelectionModel().addListSelectionListener(
                   new ListSelectionListener() {
                        public void valueChanged(ListSelectionEvent e) {
                             if (list.getSelectedIndices().length > 0)
                                  btnDelete.setEnabled(true);
                             else
                                  btnDelete.setEnabled(false);
              // Watch out for double clicks in the list and edit the document
              // selected
              list.addMouseListener(new MouseListener() {
                   public void mouseClicked(MouseEvent e) {
                        if (e.getClickCount() == 2) {
                             editPublication(
                                  listModel, (Publication) list.getSelectedValue());
                   public void mousePressed(MouseEvent e) { }
                   public void mouseReleased(MouseEvent e) { }
                   public void mouseEntered(MouseEvent e) { }
                   public void mouseExited(MouseEvent e) { }
              // Now keep an eye out for the user hitting return (will edit the selected
              // publication) or delete (will delete it)
              // Note: we have do the ugly "pressed" flag because JOptionPane closes
              // on keyPressed and we end up getting keyReleased. Can't use keyTypes
              // because it does not contain the virtual key code 8(
              list.addKeyListener(new KeyListener() {
                   boolean pressed= false;
                   public void keyTyped(KeyEvent e) { }
                   public void keyPressed(KeyEvent e) {
                        pressed= true;
                   public void keyReleased(KeyEvent e) {
                        if (pressed && e.getKeyCode() == e.VK_ENTER) {
                             editPublication(
                                  listModel, (Publication) list.getSelectedValue());
                        else if (pressed && e.getKeyCode() == e.VK_DELETE)
                             deletePublications(list, listModel);
                        pressed= false;
              // Put the list in a scroll pane so we can see it all. Make it resonably
              // wide so we don't have top scroll horizonatly to see most publications
              JScrollPane listScrollPane= new JScrollPane(list);
              listScrollPane.setPreferredSize(new Dimension(640, 300));
              // layout the list and button panel
              panel.add(listScrollPane, BorderLayout.CENTER);
              panel.add(btnPanel, BorderLayout.SOUTH);
              // ok, ready to rumble, lets show the user what we've got
              JOptionPane.showOptionDialog(
                   null, panel, "Publications",
                   JOptionPane.DEFAULT_OPTION,
                   JOptionPane.PLAIN_MESSAGE,
                   null, new String[0], null
              // leg it
              System.exit(0);

Maybe you are looking for

  • Problems installing new Adobe Flash Player

    Several web sites that I visit give the message that I need to update my Adobe Flash Player.  I go to the Adobe site and download the update and go through the install, but when I go back to the page saying that I need to update the flash player it s

  • SMTP Change

    Hello I would like to add at background en email to all our vendor using a function module. witch function should i use in order to do the same application as XK02? Thanks in advance, Emmanuel

  • InDesign CS4 won't run - 'not supported on this architecture' error

    Hi there, I'm having a problem with InDesign and Flash (both CS4), installed as a bundle in one go from Adobe Master Collection discs, When trying to launch InDesign or Flash, I get a message that they are 'not supported on this architecture'. I'm on

  • Posting Goods Receipt using DTW

    Hi Experts I am using DTW to post around 9000 Goods Receipt documents and I am having trouble getting the items to post at the correct price.   Each time I try to post SAP B1 (2007A) uses the Last Purchase Price price list even though I have a differ

  • Do you need to back up iPhone before downloading I0S7?

    I'm not sure if I need to back up my phone before updating? Yes or no?