Speed of the Math class

If I am performing a lot of calculations is it best to use a Math class function or write it yourself (best in terms of speed not accuracy).
e.g. Math.pow(a-b,2) OR (a-b) * (a-b)
I am grateful for any opinions.

Your version would allow the compiler to use the fact that the expression is completely knowable at compilation time, providing for a trivial solution for the in-line multiplication approach.
The version below avoids thatpublic class Test {
    public static void main(String[] args) {
        long start = 0;
        long end = 0;
        long powtime = 0;
        long multtime = 0;
        double x = Double.parseDouble(args[0]);
        double y = Double.parseDouble(args[1]);
        System.out.println("Starting the pow test.");
        start = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            double value = (x - y) * (x - y);
        end = System.currentTimeMillis();
        multtime = end - start;
        System.out.println(
            "By using multiplication it took: " + ((double) multtime / 1000) + " seconds.");
        start = System.currentTimeMillis();
        for (int j = 0; j < 10000000; j++) {
            double value = Math.pow((x - y), 2);
        end = System.currentTimeMillis();
        powtime = end - start;
        System.out.println(
            "By using Math.pow() it took: " + ((double) powtime / 1000) + " seconds.");
}With this I get a 6:1 (1.272 to 0.200) ratio of Math.pow() to inline multiplication time. Still a fairly large ratio.
Playing with double, int and using increasing larger values of the exponent, the Math.pow() seems to be far slower that multiplication. Of course Math.pow() can handle complex exponents (2.3645463) and take roots while the simple multiplication approach cannot.
Chuck

Similar Messages

  • Trig functions in the Math class

    One of the techniques suggested to master for the Java Programmer exam is using the trigonometry methods in the Math class. Does that mean that on the exam I would need a trigonometry knowledge or is it enough to be familiar with their signature ?

    No trig knowledge - just questions on the Java language, including method signatures. Check out the various mock exams such as at http://www.javaranch.com/certfaq.jsp

  • Java ME SDK 3.0 Math Class

    Using Eclipse and Java ME SDK 3.0
    When the Application Descriptor configuration is set to use DefaultCldcPhone1 or other emulators in the Java ME SDK 3.0 many of the Math class methods such as Math.sqrt(double arg0) are not available. However if I change the configuration to use a Nokia emulator all the Math class methods become available.
    This issue has just shown up since moving from WTK25 to Java ME SDK 3.0
    Note:
    Under Eclipse/Preferences/Java ME/Device Management the Configuration of all the emulators from the Java ME SDK 3.0 is listed as CLDC-1.0 whereas the other emulators from Nokia and from the Sun Java Wireless Toolkit 2.5 are listed as CLDC-1.1.

    It is related to the configuration of the emulator (CLDC 1.0 or CLDC 1.1)...
    If the configuration is CLDC 1.0 all the floating point data types (float, double, Float, Double) will not be available...
    If you change the configuration to CLDC1.1 , then all the previous types will be available.
    PS: I don't know how to do this in EclipseME

  • Why Math class does not have any constructor.

    Math class does not have any constructor.
    But all the classes have a default constructor. Then why the math class is not having any constructor. Is math class having some other constructor or is the default constructor concept applicable only for user defined classes.

    Math class does not have any constructor.
    But all the classes have a default constructor. Then
    why the math class is not having any constructor. Is
    math class having some other constructor or is the
    default constructor concept applicable only for user
    defined classes.You cannot instantiate a new Math object, nor can you extend the Math class. All you can do is use Math's static methods and variables. Its a utility class, thats what its susposed to do.
    JJ

  • Extending Math class

    As I understand, in actionscript 2 you could extend flash's Math class to add your own functions, but this is no longer possible in actionscript 3.  I want to add a mod() function to the Math class, and I'm assuming I have to write a wrapper class to accomplish this.  How do I import the existing Math class into my MathPlus or whatever class?  Also, is there anything else I should know about this?

    Thanks for the replies (very good to know about %).  The only reason I would prefer to extend Math or build a wrapper around it is if I were to write a sufficient number of additions such that trying to remember which were in Math and which were in my custom class became difficult.  I just think it would be nice to have access to all of my (and Flash's) math related code within one class.
    It just occurs to me that I just need to make functions in my class that call the ones in Math.

  • Question for the math lovers!  Using while loop and exponents

    Hi there Java geniuses! ; ) A little question here that has been perplexing me for the past few days. I'm trying to create a class that contains a single static method as follows:
    public static double exp(double a)
    It's supposed to work to calculate an "exp" value much like the Math.exp method of the Math class. Essentially, I need to keep calculating approximations of "exp" until a certain condition is met. This condition is specified in a while loop. Following is what I've written so far. But I can't seem to get the thing to work properly. Any suggestions/ advice would be greatly appreciated! Thanks.
    A class that computes the "exp" for a user-defined
    value.
    public class MyMath
    public static double exp(double x)
    double dbloldGuess;
    double dblnewGuess = 1 + x; // First value for newGuess
    double dblcounter = 1;
    do
    dblcounter++; // increments counter
    dbloldGuess = dblnewGuess;
    dblnewGuess = dbloldGuess + ((x ** dblcounter) / counter);
    while (Math.abs((newGuess - oldGuess) / newGuess) > 1e-15);
    return x;
    }

    ** wasn't an operator in C when I last checked...
    Anyway here's my lousy attempt:public static double exp(double a) {
            double guess = 1;
            int N = 18;
            while (N --> 1) guess = 1 + a/N * guess;
            return guess;
    }When called with 1.0 as argument gives the value equal to the constant Math.E, so is "probably" ok for arguments 0.0 -- 1.0. I wont guarantee anything else because this method is pretty pathological when it comes to loss of precision due to rounding, even if you increase N.

  • Question about Math Class

    I have a couple of Java questions I was wondering if anyone could answer:
    1). In this one statement, which takes the greatest common denominator and places it in the variable commom:
    int common = gcd (Math.abs(numerator), denominator);
    A).What is gcd? I looked it up and it's not a reserved word in the math class. In the class that this statement comes from there is no variable, object, or method named gcd. There is also no gcd variable, object, or invoked method in the client code that uses the class that this statement comes from.
    B ). I know that abs is a method of the math class for the absolute value of a number(in this case the number inside the variable numerator.). And I know that when the abs method is invoked it sends the variable 'numerator' as the parameter for the data to take the absolute value of. What I don't understand is the syntax of this statement in regards to how you can take the absolute value of the variable 'denominator' haveing a variable 'numerator' inclosed in the parenthesis and simpley adding a comma to include the variable 'denominator' in the argument to be sent in the invocation of the abs method. It seems like this would be the correct syntax:
    int common = (Math.abs(numerator))/(Math.abs(denominator));
    Can anyone explain the 'int common = gcd (Math.abs(numerator), denominator);'
    statement?
    Thanks,
    -dman

    > A).What is gcd?
    As already been said: it's the Greatest Common Divider.
    Example: fraction 9/24, then gcd(9, 24) == 3.
    >It seems like this would be the correct syntax:
    int common = (Math.abs(numerator))/(Math.abs(denominator));
    Probably the gcd(...) method is used to normalize a fraction whose denominator is always positive. If the fraction is smaller then zero, the numerator is negative. And to caculate the Greatest Common Divider of two numbers, the gcd(...) method needs two positive arguments.
    Google for "Euclid GCD algorithm".

  • Is there a way to speed up the pace of the video (watch in fast-forward) I am watching?

    I am watching a class lesson that is 3 hours long and my teacher talks extremely slow. Is there a way to speed up the pace of my video? I know on some video players you can watch a video in 1.5, 2.0, 2.5 etc. levels of fast forward.

    Have you got the drives set up to spin down when not in use?
    Have a look at the Energy Saver settings in System Preference on the Mac.
    Make sure the "Put the Hard Discs to sleep when possible" box is not ticked.

  • Speeding up the Get-MailboxStatistics cmdlet for ~19K mailboxes.

    Greetings,
    While this is partially a PowerShell scripting question, I am posting it in the Exchange 2010 forum because the issues I believe center around the Get-MailboxStatistics itself, and the speed of my scripts in Exchange 2010 (possibly
    due to the additional overhead in remote PowerShelling).
    In my Exchange 2010 system we have ~19,000 mailboxes spread accross multiple DAG nodes, and ever since we upgraded from Exchange 2007 to Exchange 2010, gathering all of the mailboxes and then gathering their statistics takes almost
    twice as long. For example a script that used to take ~45 minutes in Exchange 2007, takes about an hour and a ½.
    The issue I am running into when clocking core aspects of a mailbox data gathering scripts is that the Get-MailboxStatistics seems to be taking an excessively long period of time, and I am hoping someone can help me figure out a
    way to speed up the process.
    For example this is a boiled down script I created, where I ripped out a ton of other things and just focused on the Get-Mailbox and Get-MailboxStatistics commands:
    $BaseOU
    =
    "Customers"
    # Capture the date and time in a variable using the "Fri 11/01/2010 6:00 AM" format.
    $DateTime
    =
    Get-Date
    -Format
    "ddd MM/dd/yyyy h:mm tt"
    # Select a single domain controller to use for all the queries (to avoid mid AD replication inconsistencies)
    from the environment variable LOGONSERVER - this ensures the variable will always be dynamically updated.
    $DomainController
    = ($Env:LogonServer).Substring(2)
    # Set the loop count to 0 so it can be used to track the percentage of completion.
    $LoopCount
    = 0
    # Start tracking the time this script takes to run.
    $StopWatch1
    =
    New-Object
    System.Diagnostics.Stopwatch
    $StopWatch1.Start()
    # Get the mailbox info for all IHS customer mailboxes.the storage limit is Prohibit send or mailbox disabled
    Write-Host
    -ForegroundColor
    Green
    "Beginning mailbox gathering. In a short while a progress bar will appear."
    $GatheredMailboxes
    =
    Get-Mailbox
    -ResultSize:Unlimited
    -OrganizationalUnit
    "ADDomain.com/$BaseOU"
    -DomainController
    $DomainController |
    Select Identity,DisplayName,ProhibitSendQuota
    Write-Host
    -ForegroundColor
    Green
    "Mailbox data gathering is complete."
    $StopWatch1.Stop()
    $StopWatch2
    =
    New-Object
    System.Diagnostics.Stopwatch
    $StopWatch2.Start()
    Foreach ($Mailbox
    in
    $GatheredMailboxes) {
    # Show a status bar for progress while the mailbox data is collected.
    $PercentComplete
    = [Math]::Round(($LoopCount++
    $GatheredMailboxes.Count
    * 100),1)
    $CurrentMBDisplay
    =
    $Mailbox.DisplayName
    Write-Progress
    -Activity
    "Mailbox Data Gathering in Progress"
    -PercentComplete
    $PercentComplete
    `
    -Status
    "$PercentComplete% Complete"
    -CurrentOperation
    "Current Mailbox: $CurrentMBDisplay"
    #Get the mailbox statistics for each mailbox gathered above.
    $MailboxStats
    =
    Get-MailboxStatistics
    $Mailbox.Identity |
    Select StorageLimitStatus,TotalItemSize
    # Proceed only if the the mailbox statistics show the storage limit is Prohibit Send or Mailbox Disabled.
    # Write-Host "Stats for"$Mailbox.DisplayName"are Limit ="$MailboxStats.StorageLimitStatus"and Size ="$MailboxStats.TotalItemSize.Value.ToMB()"MB."
    # Calculate the amount of time the script took to run and write the information to the screen.
    $StopWatch2.Stop()
    $ElapsedTime
    =
    $StopWatch1.Elapsed
    Write-Host
    "he mailbox gathering took"
    $ElapsedTime.Hours
    "hours,"
    $ElapsedTime.Minutes
    "minutes, and"
    $ElapsedTime.Seconds
    `
    "seconds to run."
    $ElapsedTime
    =
    $StopWatch2.Elapsed
    Write-Host
    "The foreach loop took"
    $ElapsedTime.Hours
    "hours,"
    $ElapsedTime.Minutes
    "minutes, and"
    $ElapsedTime.Seconds
    `
    "seconds to run."
    Using the two stop clocks, I was able to see that the Get-Mailbox of all mailboxes took ~9 minutes. That isn’t lightning fast, but it isn’t unreasonable.
    The issue comes in where the Foreach loop with the Get-MailboxStatistics took ~53 minutes, and I am sure some of the mailbox data was cached on the servers from my various tests so it would probably take even longer with a cold
    run.
    I did some digging around and I really couldn’t find anything on how to speed up the Get-MailboxStatistics, and the only thing I found was this link:
    http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/9ceefddd-7a59-44ec-8fc0-8de244acb58b
    However I am not clear on how moving the Get-MailboxStatistics into the Get-Mailbox syntax (which is odd to me in general) would speed things up if I still have to have a foreach loop to process the data a little bit and add the
    users to a datatable. That discussion also made think the foreach loop itself is slowing things down but unclear as to how/why if that is true. 
    Can someone help share some ideas on how to speed up this process? I think there are some other things I could try but I can’t think of them.
    Thank you in advance.

    I think it's impossible to speed up the Get-MailboxStatistics when it is being called for each and every mailbox individually.
    I read somewhere in other posts people were having better performance by calling the cmdlet against an entire database or server so I gave it a shot with this code:
    $DAGS = "EXCHDAG1"
    # Start tracking the time this script takes to run.
    $StopWatch = New-Object System.Diagnostics.Stopwatch
    $StopWatch.Start()
    $MailboxStatistics = New-Object System.Data.DataTable “MailboxStatistics”
    $MailboxStatistics.Columns.Add("TotalitemSize",[String]) | Out-Null
    $MailboxStatistics.Columns.Add("ItemCount",[String]) | Out-Null
    $MailboxStatistics.Columns.Add("LastLogonTime",[String]) | Out-Null
    $MailboxStatistics.Columns.Add("LastLogoffTime",[String]) | Out-Null
    $MailboxStatistics.Columns.Add("MailboxGUID",[String]) | Out-Null
    $MailboxStatistics.PrimaryKey = $MailboxStatistics.Columns["MailboxGUID"]
    ForEach ($DAGServer in (Get-DatabaseAvailabilityGroup $DAGS).Servers) {
    ForEach ($MailboxStats in (Get-MailboxStatistics -Server $DAGServer.Name | Where {$_.DisconnectDate -eq $Null})) {
    $NewMBXStatsDTRow = $MailboxStatistics.NewRow()
    $NewMBXStatsDTRow.TotalitemSize = $MailboxStats.TotalItemSize
    $NewMBXStatsDTRow.ItemCount = $MailboxStats.ItemCount
    $NewMBXStatsDTRow.LastLogonTime = $MailboxStats.LastLogonTime
    $NewMBXStatsDTRow.LastLogoffTime = $MailboxStats.LastLogoffTime
    $NewMBXStatsDTRow.MailboxGUID = $MailboxStats.MailboxGuid.ToString()
    $MailboxStatistics.Rows.Add($NewMBXStatsDTRow)
    $StopWatch.Stop()
    $ElapsedTime = $StopWatch.Elapsed
    Write-Host "The script took" $ElapsedTime.Hours "hours," $ElapsedTime.Minutes "minutes, and" $ElapsedTime.Seconds `
    "seconds to run."
    Here are the results in speed:
    The script took 0 hours, 3 minutes, and 13 seconds to run.
    So yeah... ~3 minutes versus ~1 hour, I would say that's an improvement.
    Now I will go back to my script and as I process each mailbox I will pull it's statistics information out of the DataTable using its GUID with:
    If ($MailboxStats = $MailboxStatistics.Rows.Find($Mailbox.MailboxGUID)) {
    # Insert mailbox statistics processing here using the $MailboxStats variable with "." extensions.
    } Else {
    # Mailbox statistics weren't found so go grab them individually as a backup mechanism for scenarios when a user's mailbox got moved out of the DAG to a non-DAG database for whatever reason.
    It's a little silly that I have to extract the information out of each DAG server and put it in an in-memory table just to speed this process up, but clearly there is overhead with the Get-MailboxStatistics cmdlet and grabbing more mailboxes at once helps
    negate this issue.
    I'm going to mark my own response as an answer because I don't think anyone else is going to come up with something better than what I put together.

  • Execute jar file: "could not find the main class" program will terminate

    Hey,
    I am new to Java. I have started to make a small java program which supposed to help me at my studies to lean the Dominic Memory System. I have used the latest version of Netbeans 5.5.1 to build my program in. I have two problems which I cannot figure out how to solve, please help me.
    The first problem is that the java script I have made works when I compile it in Netbeans, but when I create a Jar file it does not work. I receive a pop up message in windows ?could not find the main class program will terminate? when I execute the jar file.
    The second problem I have is that I need to compare the strings generated by the "numbers" and "TIP" and if the numbers is not identical the numbers in the ?Center? JPanel should be highlighted as red.
    If anyone would like to clean up the code I would be pleased. I have copied quite a lot from anyone because of my one lack of knowledge.
    * GoListener.java
    * Created on 12. september 2007, 21:48
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package grandmaster;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Vector;
    import java.util.StringTokenizer;
    import java.awt.Color;
    * @author Computer
    public class GoListener implements ActionListener {
    private JTextField viewer;
    private JTextField TIP;
    private JTextField freq;
    private JTextField max_num;
    private Vector numbers;
    public GoListener(JTextField j,JTextField k, JTextField m, JTextField f, Vector n) {
    freq = f;
    max_num = m;
    viewer = j;
    numbers = n;
    TIP = k;
    public void actionPerformed(ActionEvent e){
    int time = Integer.valueOf(max_num.getText());
    int f = Integer.valueOf(freq.getText());
    if (e.getActionCommand() == "GO") {
    for (int i = 0; i< time;++i) {
    int number=0;
    number = (int)Math.floor(100*Math.random());
    while(number>51){
    number = (int)Math.floor(100*Math.random());
    if(number<=9){
    viewer.setText(" "+"0" + String.valueOf(number) + " ");
    } else{
    viewer.setText(" " + String.valueOf(number) + " ");
    viewer.paintImmediately(viewer.getBounds());
    numbers.add(number);
    try {
    Thread.sleep(f*1000);
    } catch (Exception exp) {
    viewer.setText(" XX ");
    viewer.paintImmediately(viewer.getBounds());
    if (e.getActionCommand() == "VIEW") {
    try {
    //int numb = Integer.valueOf( TIP.getText() ).intValue();
    StringTokenizer tokenizer = new StringTokenizer(TIP.getText(), " ");
    String[] split = null;
    int tokenCount = tokenizer.countTokens();
    if (tokenCount > 0) {
    split = new String[tokenCount];
    for (int current = 0; current < tokenCount; current++) {
    split[current] = tokenizer.nextToken();
    viewer.setText(" " + String.valueOf(numbers) + " ");
    // k=numbers(1);
    /*while(c<i){
    String.valueOf(k).equals(split[1]);
    c++;
    TIP.setText(" " + split[2] + " ");
    } catch (Exception exp) {
    try {
    //string testit = numb.toString();
    //String str = "" + numb;
    //viewer.setText(str);
    //viewer.setText(numbers.toString());
    numbers.clear();
    } catch (Exception exp) {
    * Main.java
    * Created on 12. september 2007, 21:07
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package grandmaster;
    import java.util.Vector;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.JButton;
    import java.awt.*;
    import grandmaster.GoListener;
    * @author Computer
    public class Main extends JFrame {
    private JTextField viewer;
    public JTextField TIP;
    // private TextInputPanel TIP;
    private Vector numbers;
    /** Creates a new instance of Main */
    public Main() {
    numbers = new Vector();
    JPanel p = new JPanel(new GridLayout(0,4));
    JButton go = new JButton();
    JButton view_num = new JButton();
    go.setText("Go!");
    go.setVisible(true);
    go.setActionCommand("GO");
    view_num.setText("VIEW");
    view_num.setVisible(true);
    view_num.setActionCommand("VIEW");
    JTextField max_num = new JTextField();
    max_num.setText("5");
    JTextField freq = new JTextField();
    freq.setText("1");
    viewer = new JTextField();
    viewer.setText("XX");
    TIP = new JTextField("");
    p.add(go);
    p.add(max_num);
    p.add(freq);
    p.add(view_num);
    getContentPane().add(p,BorderLayout.NORTH);
    getContentPane().add(viewer,BorderLayout.CENTER);
    getContentPane().add(TIP,BorderLayout.SOUTH);
    setSize(200,200);
    GoListener g = new GoListener(viewer,TIP,max_num, freq, numbers);
    go.addActionListener(g);
    view_num.addActionListener(g);
    * @param args the command line arguments
    public static void main(String[] args) {
    // TODO code application logic here
    Main window = new Main();
    window.setVisible(true);
    }

    NetBeans questions should be posted to the NB site. It has mailing lists and associated forums.
    This tutorial from the NB site addresses running programs outside of NB
    http://www.netbeans.org/kb/articles/javase-deploy.html
    When you compare objects, use ".equals()" and reserve == for comparing values.

  • Trying to do the math... (HDD related)

    Hi,
    I am putting together a new PC for editing and was wondering, how fast a HDD really has to be?! I read all the FAQ and understand, that there are plenty of suggestions out there, on how to setup your HDD's! However, I would like to be able to do the math myself and understand, why a given setup is recommended! If I take some 4K Cin footage of my GoPro Hero 3 BE, and enter the information here:
    http://web.forret.com/tools/video_fps.asp?width=4096&height=2160&fps=15&space=rgb444&depth =10 
    (4096 x 2160, 15FPS, RGB 4:4:4 and 10 bits/color... I just picked something for demonstration purposes only) it tells me, that the Uncompressed bitrate is 497,66 MB/s.
    If I now look at a chart like this:
    http://www.tomshardware.com/charts/hdd-charts-2013/-01-Read-Throughput-Average-h2benchw-3. 16,2901.html 
    and pick a HDD, with lets say 150MB/s, what does this now mean?! The bitrate is clearly higher than the "speed" of the HDD. Does this mean, my playback is going to be jerky?! I believe so, but I am not sure what part a graphics Card plays here?! I also understand, that a slow HDD, can act as the bottle neck of a given system. So no matter how fast your CPU is, a slow HDD setup will slow the whole system down. But how fast does a HDD really have to be, so it doesn't slow the system down?! Is there some way to do the math and know in advance, what is going to work and what not?! Or is it as simple as picking a SD card for a GoPro?! If my video format delivers, lets say 500MB/s, I would need a SD card that is at LEAST this fast, so it can capture the video without dropping frames, right?! At least this is how I understand it, ha ha.
    It must work a little bit different on a PC though, since the footage doesn't have to be captured in real time, correct?! A slow HDD is now going to just increase render times, right?!
    G, I am so tired of trying to explain, what I mean, LOL. Hopefully all of this will make sense to someone out there?!
    thanks,
    KMD
    p.s. Maybe it is really as simpe as just taking the bitrate for one track, adding all tracks up and whatever number comes up, your HDD has to be at least that fast, LOL?!

    SAFEHARBOR11 wrote:
    The 8-drive RAID reference was in regards to the "4:4:4 10-bit uncompressed HD" example that you offered. I sell those drives, part of my job, that is how I know. But this does not apply to GoPro footage, the above example is very rare, stuff Hollywood-types might use and not for you or I to worry about.
    Black Magic Design has a drive speed test utility that you can run and it will tell you what video formats will work with your drive setup. There are also charts and tools out there, such as AJA Data Rate Calculator for PC or Mac, and now available from Apple App Store for iPhones - http://www.aja.com/en/software
    Please note when playing with the calculator that if the format is "8-bit" or "10-bit" that references UNCOMPRESSED video, and you are not working with that. Since the calculator doesn't list the GoPro (Cineform) codec, not sure what the data rate is going to be, but much lower for sure.
    Looking at the requirements for GoPro Studio Premium, they are recommending a 7200rpm unit, and fast connection if external, but nothing fancy so I wouldn't worry about needing any special drives.
    Thanks
    Jeff Pulera
    Safe Harbor Computers
    Jeff,
    I am planning on using 4k in the near Future, so I need to worry about it, ha ha. The other thing is, a tool that measures my drive speed is useless for me, as of right now, since I do not have a system yet! Working on putting one together as we "speak". Anyhow, you pointing out the AJA Data Rate Calculator to me, is what made me realize, that I had the answer in front of me, the whole time!
    http://web.forret.com/tools/video_fps.asp?width=4096&height=2160&fps=15&space=rgb444&depth =10
    Either AJA or this site, will help me figuring out the data rate of most video formats... I have no idea why I didn't realize that the first time?! I read my OP and I want to delete it, ha ha...
    Thanks again for all the help!
    KMD

  • Unable to compile the java class in the SQL PLUS

    Hi Team,
    I am unable to compile the java class in the SQL PLUS in dev1 and dev2. It is giving the following error.
    But the same class get Compiled in the Toad(Tool) without any error and working fine. Could someone help me
    What to do for this for your reference ,Attaching the java class file.
    “ORA-29536: badly formed source: Encountered "<EOF>" at line 1, column 28.
    Was expecting one of:
    ----------------------Here is the Java class Code.....................
    create or replace and compile java source named "XXVM_ZipFileUtil_Ela"
    as
    import java.math.BigDecimal;
    import java.util.zip.Deflater;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    import oracle.sql.*;
    import oracle.jdbc.*;
    import java.sql.*;
    import java.io.*;
    public class XXVM_ZipFileUtil_Ela
    public static oracle.sql.BLOB getZipFile(
    oracle.sql.CHAR zipFilePathCHAR, oracle.sql.CHAR zipFileNameCHAR,
    int fileBufferSize, int zipFileBufferSize,
    boolean deleteZipFile, java.sql.Array fileNames, java.sql.Array fileContents, java.sql.Array fileContentsLength)
    throws IllegalArgumentException, FileNotFoundException, IOException, java.sql.SQLException
    String zipFilePath = (zipFilePathCHAR == null) ? null : zipFilePathCHAR.stringValue();
    String zipFileName = (zipFileNameCHAR == null) ? null : zipFileNameCHAR.stringValue();
    String zipPathAndFileName = new String(
    new String(zipFilePath == null || zipFilePath == "" ? "/tmp/" : zipFilePath) +
    new String(zipFileName == null || zipFileName == "" ? System.currentTimeMillis() + ".zip" : zipFileName));
    byte[] buffer = new byte[fileBufferSize == 0 ? 100000000 : fileBufferSize];
    try
    Connection conn = DriverManager.getConnection("jdbc:default:connection:");
    oracle.sql.CLOB[] fileContentsCLOB = (oracle.sql.CLOB[])fileContents.getArray();
    String[] fileNamesString = (String[])fileNames.getArray();
    BigDecimal[] fileContentsLengthNumber = (BigDecimal[])fileContentsLength.getArray();
    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPathAndFileName));
    zipOut.setLevel(Deflater.DEFAULT_COMPRESSION);
    for (int i = 0; i < fileNamesString.length; i++) {
    System.out.println(i);
    zipOut.putNextEntry(new ZipEntry(fileNamesString));
    InputStream asciiStream = fileContentsCLOB[i].getAsciiStream(1L);
    int asciiReadCount = asciiStream.read(buffer,0,fileContentsLengthNumber[i].intValue());
    zipOut.write(buffer, 0, fileContentsLengthNumber[i].intValue());
    zipOut.closeEntry();
    zipOut.close();
    byte zipFileContents[] = new byte[zipFileBufferSize == 0 ? 100000000 : zipFileBufferSize];
    FileInputStream zipIn = new FileInputStream(zipPathAndFileName);
    int byteCount = zipIn.read(zipFileContents);
    zipIn.close();
    byte returnFileContents[] = new byte[byteCount];
    System.arraycopy(zipFileContents,0,returnFileContents,0,byteCount);
    String returnFileContentsString = new String(returnFileContents);
    if (deleteZipFile)
    boolean deletedFile = (new File(zipPathAndFileName)).delete();
    oracle.sql.BLOB returnFileContentsBLOB = null;
    returnFileContentsBLOB = BLOB.createTemporary(conn, true, BLOB.DURATION_SESSION);
    returnFileContentsBLOB.open(BLOB.MODE_READWRITE);
    //OutputStream tempBlobWriter = returnFileContentsBLOB.getBinaryOutputStream();
    OutputStream tempBlobWriter = returnFileContentsBLOB.setBinaryStream(1);
    tempBlobWriter.write(returnFileContents);
    tempBlobWriter.flush();
    tempBlobWriter.close();
    returnFileContentsBLOB.close();
    return returnFileContentsBLOB;
    catch (IllegalArgumentException ex) {
    ex.printStackTrace();
    throw ex;
    catch (FileNotFoundException ex) {
    ex.printStackTrace();
    throw ex;
    catch (IOException ex)
    ex.printStackTrace();
    throw ex;
    catch (java.sql.SQLException ex)
    ex.printStackTrace();
    throw ex;

    860411 wrote:
    Hi Team,
    I am unable to compile the java class in the SQL PLUS in dev1 and dev2. It is giving the following error.
    But the same class get Compiled in the Toad(Tool) without any error and working fine. Could someone help me
    What to do for this for your reference ,Attaching the java class file.
    “ORA-29536: badly formed source: Encountered "<EOF>" at line 1, column 28.
    Was expecting one of:
    I believe the error message is clear and self-explanatory.
    ----------------------Here is the Java class Code.....................
    create or replace and compile java source named "XXVM_ZipFileUtil_Ela"
    as
    import java.math.BigDecimal;
    import java.util.zip.Deflater;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    import oracle.sql.*;
    import oracle.jdbc.*;
    import java.sql.*;
    import java.io.*;
    public class XXVM_ZipFileUtil_Ela
    public static oracle.sql.BLOB getZipFile(
    oracle.sql.CHAR zipFilePathCHAR, oracle.sql.CHAR zipFileNameCHAR,
    int fileBufferSize, int zipFileBufferSize,
    boolean deleteZipFile, java.sql.Array fileNames, java.sql.Array fileContents, java.sql.Array fileContentsLength)
    throws IllegalArgumentException, FileNotFoundException, IOException, java.sql.SQLException
    String zipFilePath = (zipFilePathCHAR == null) ? null : zipFilePathCHAR.stringValue();
    String zipFileName = (zipFileNameCHAR == null) ? null : zipFileNameCHAR.stringValue();
    String zipPathAndFileName = new String(
    new String(zipFilePath == null || zipFilePath == "" ? "/tmp/" : zipFilePath) +
    new String(zipFileName == null || zipFileName == "" ? System.currentTimeMillis() + ".zip" : zipFileName));
    byte[] buffer = new byte[fileBufferSize == 0 ? 100000000 : fileBufferSize];
    try
    Connection conn = DriverManager.getConnection("jdbc:default:connection:");
    oracle.sql.CLOB[] fileContentsCLOB = (oracle.sql.CLOB[])fileContents.getArray();
    String[] fileNamesString = (String[])fileNames.getArray();
    BigDecimal[] fileContentsLengthNumber = (BigDecimal[])fileContentsLength.getArray();
    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPathAndFileName));
    zipOut.setLevel(Deflater.DEFAULT_COMPRESSION);
    for (int i = 0; i < fileNamesString.length; i++) {
    System.out.println(i);
    zipOut.putNextEntry(new ZipEntry(fileNamesString));
    InputStream asciiStream = fileContentsCLOB[i].getAsciiStream(1L);
    int asciiReadCount = asciiStream.read(buffer,0,fileContentsLengthNumber[i].intValue());
    zipOut.write(buffer, 0, fileContentsLengthNumber[i].intValue());
    zipOut.closeEntry();
    zipOut.close();
    byte zipFileContents[] = new byte[zipFileBufferSize == 0 ? 100000000 : zipFileBufferSize];
    FileInputStream zipIn = new FileInputStream(zipPathAndFileName);
    int byteCount = zipIn.read(zipFileContents);
    zipIn.close();
    byte returnFileContents[] = new byte[byteCount];
    System.arraycopy(zipFileContents,0,returnFileContents,0,byteCount);
    String returnFileContentsString = new String(returnFileContents);
    if (deleteZipFile)
    boolean deletedFile = (new File(zipPathAndFileName)).delete();
    oracle.sql.BLOB returnFileContentsBLOB = null;
    returnFileContentsBLOB = BLOB.createTemporary(conn, true, BLOB.DURATION_SESSION);
    returnFileContentsBLOB.open(BLOB.MODE_READWRITE);
    //OutputStream tempBlobWriter = returnFileContentsBLOB.getBinaryOutputStream();
    OutputStream tempBlobWriter = returnFileContentsBLOB.setBinaryStream(1);
    tempBlobWriter.write(returnFileContents);
    tempBlobWriter.flush();
    tempBlobWriter.close();
    returnFileContentsBLOB.close();
    return returnFileContentsBLOB;
    catch (IllegalArgumentException ex) {
    ex.printStackTrace();
    throw ex;
    catch (FileNotFoundException ex) {
    ex.printStackTrace();
    throw ex;
    catch (IOException ex)
    ex.printStackTrace();
    throw ex;
    catch (java.sql.SQLException ex)
    ex.printStackTrace();
    throw ex;
    The last two lines above should be
    /Srini

  • [svn:osmf:] 13027: Fix bug in SerialElement where the durationReached event was dispatched on a child-to-child transition due to the base class thinking that the duration had been reached  (since the second child didn't have a duration yet).

    Revision: 13027
    Revision: 13027
    Author:   [email protected]
    Date:     2009-12-16 18:09:46 -0800 (Wed, 16 Dec 2009)
    Log Message:
    Fix bug in SerialElement where the durationReached event was dispatched on a child-to-child transition due to the base class thinking that the duration had been reached (since the second child didn't have a duration yet).  Injection from trait refactoring.
    Modified Paths:
        osmf/trunk/framework/MediaFramework/org/osmf/composition/CompositeTimeTrait.as

    http://ww2.cs.fsu.edu/~rosentha/linux/2.6.26.5/docs/DocBook/libata/ch07.html#excatATAbusErr wrote:
    ATA bus error means that data corruption occurred during transmission over ATA bus (SATA or PATA). This type of errors can be indicated by
    ICRC or ABRT error as described in the section called “ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION)”.
    Controller-specific error completion with error information indicating transmission error.
    On some controllers, command timeout. In this case, there may be a mechanism to determine that the timeout is due to transmission error.
    Unknown/random errors, timeouts and all sorts of weirdities.
    As described above, transmission errors can cause wide variety of symptoms ranging from device ICRC error to random device lockup, and, for many cases, there is no way to tell if an error condition is due to transmission error or not; therefore, it's necessary to employ some kind of heuristic when dealing with errors and timeouts. For example, encountering repetitive ABRT errors for known supported command is likely to indicate ATA bus error.
    Once it's determined that ATA bus errors have possibly occurred, lowering ATA bus transmission speed is one of actions which may alleviate the problem.
    I'd also add; make sure you have good backups when ATA errors are frequent

  • Is it possible to put the java classes of an application and run?

    Hi All,
    Please excuse me if this question seems meaningless / laughable.
    We get java class files by compiling the source code with java compiler. To run the application, classpath can be set to the folder where the class files are stored and then run the main class.
    Now the question is, is it possible to read the class files to RAM and then run the application. I highly appreciate your help.
    Thanks in advance.
    Chinnaswamy

    You could
    1.) copy the class files to a ramdisk
    2.) write another class loader that deletes the class files after loading >them from ram
    but all of this is probably not necessary.
    What exactly would you like to achieve by doing this? Thanks, JoachimSauer.
    The idea I have in mind is to first read and store the java class files in C/C++ code and then while running the C/C++ code, read & put the java classes into RAM and run the java application.
    This way the decompilation problem can be alleviated for valuable java applications. ( I am not sure, this will work)
    Another reason could be speed improvement. Classes in RAM is expected to make the application to run faster than when class files are in hadr disk
    With regards
    Chinnaswamy

  • Can anyone help me with this program using the Scanner Class?

    I have to write a program that asks for the speed of a vehicle (in miles-per-hour) and the number of hours it has traveled. It should use a loop to display the distance a vehicle has traveled for each hour of a time period specified by the user. Such as 1 hour will equal 40 miles traveled, 2 hours will equal 80, 3 hours will equal 120, etc. This is what I've come up with thus far. Any help is appreciated.
    import java.util.Scanner;
         public class DistanceTraveled
              public static void main(String[] args)
                   int speed;
                   int hours;
                   int distance;
                   Scanner keyboard = new Scanner(System.in);
                   System.out.print("What is the speed of the vehicle in miles-per-hour?");
                   speed = keyboard.nextInt();
                   System.out.print("How many hours has the vehicle traveled for?");
                   hours = keyboard.nextInt();
                   distance = speed*hours;
                   while (speed < 0)
                   while (hours < 1)
                   System.out.println("Hour     Distance Traveled");
                   System.out.println("------------------------");
                   System.out.println(hours + " " + distance);
    }

    When you post code, wrap it in code tags. Highlight it and click the CODE button above the text input area.
    You seem to be trying to reuse the speed and hours variables in your loop. That's probably a mistake at this point. Keep it simpler by defining a loop variable.
    Also I don't see the need for two loops. You just want to show how far the vehicle has traveled for each one-hour increment, assuming constant speed, for the number of hours it has been traveling, right? So a single for loop should be sufficient.

Maybe you are looking for