Conversion or Casting................

Hi
I think i got a superb question.:)Let me explain u first.
Widening Conversion:::
A conversion that accommodate wider range of values than the original type.e.g.,
int in=25;
double d=in; //is legal
because int in is 32 bit and double d is 64 bit.
int ---> double
My Question:::
According to defination of Conversion , how it is possible to assign long value to float with out casting???
long lng=10;
float fl=lng;//it is legal. why????
because long is 64 bit and float is 32 bit.
Is there any Duke $ for a superb question. lmao :)
Thank you
Jafery

I think it's not really only a memory problem.
In "int"-like types the information is stored usign directly binary coding:
00000000 = 0, 00000001 = 1, 00000010 = 2, 00000011 = 3, ...
whereas in "float"-like types it's much more complex:
what you keep in your memory are, in fact, two numbers.
One of them is an exponent (x), the other a multiplication constant (c). Your number is constructed as follows:
c. exp(x), where exp(x) returns e^x (e = 2.718... I'm sure you've seen this number before)
Of course, ideally c (but not necessarily x) should be also a real number (otherwise you loose a possibility of unlimited precission), but it is not possible (computers are discrete machines). For x and c binary coding ("int"-like) is used (I used to know the exact algorithm. I think 0<=c<1, ... something like 0.00111011110011 - quite funny, isn't it?
and x is 8bit signed int - at least for float)
If you start to think deeply about it, the conversion to floats can never be 100%ly precise. It is the reason why comparing some calculated floats to a constant/variable may fail:
Ex. square equation: (x-x0)^2 + (y-y0)^2 = r^2 will never work, what you have to do is
(x-x0)^2 + (y-y0)^2 - r^2 < delta)

Similar Messages

  • Conversion/Type Cast of sys.XMLType to NUMBER and VARCHAR2

    How do we typecast or convert a variable of the type sys.XMLType to NUMBER and VARCHAR2?
    For e.g. I have a variable :-
    v_STATE sys.XMLType
    I want to convert it to either of the type NUMBER or VARCHAR2.

    How do we typecast or convert a variable of the type sys.XMLType to NUMBER and VARCHAR2?
    Your question is too vague to give a relevant answer.
    Typecasting doesn't make sense in this situation, XMLType is an opaque datatype, it's not like converting VARCHAR2 to NUMBER (or vice versa).
    Do you mean serializing the XML document, or extracting atomic node values, or something else ?
    Depending on your requirement, you may want to look for XMLSerialize() or XMLCast() functions.
    And on a side note, don't always expect people to search for your previous threads to find some useful information, such as a db version...

  • Casting conversion in JLS3 draft

    Seems to be missing a post-boxing widening reference conversion:class C {
      Object o1 = (Comparable<Float>)1.0f; // ok
      Object o2 = (java.io.Serializable)false; // ok
    }Please ignore the Objects on the left-hand-sides - they are there only to give the casts somewhere to exist.
    Anyway, "5.5 Casting Conversion" says: "Casting contexts allow the use of ...a boxing conversion (�5.1.7)." but it there is no optional post-boxing widening reference conversion as there is under assignment conversion and method invocation conversion. Given that fact, it seems that those two statements shouldn't compile, or the jls should change.

    Actually, if you notice, I specifically mention boxing.
    You're right that Float->Object ends up as a nop in the bytecode, and it is allowed by the draft jls3.
    But float->Float->Object does not work out to a nop in the bytecode - a Float is actually allocated.
    In any case, what happens in the bytecode or internally in the compiler is sort of irrelevant, because according to the draft jls3, the two statements in the example should never make it past the compiler.
    You can't have a cast of the form (Type)arg if arg's compile-time type is not convertible to Type via "casting conversion"... and "float" is not casting-convertible to "Object" according to the rules of the draft jls3.
    Of course, it's probably just an omission in the spec itself and not cause for alarm.

  • Java Types Conversting & Casting .

    Hi All !
    Really i do have two questions regarding Java Type Conversion and Casting
    and hope i would find (good) answers :
    [Q1:]
    why it's legal to convert(implicitly) from ( long --> float ) and this is
    said to be a widening conversion even if the size of long is longer than float
    and hence there a possible loss of information ?
    [Q2:]
    why it's legal to cast(explicitly) from ( byte --> char ) and how compiler will deal
    with byte as singed and char as unsigned during type casting (this is said to be
    a narrowing converstion and it is really is ) ?
    for [Q2:] i did the follwing code :
    public class TestNarw
         public TestNarw()
              byte bBefore=-100; // change this value to whatever negative number that is to fit in a byte.
              char c=(char)bBefore;
              byte bAfter=(byte)c;
              System.out.println(bBefore);
              System.out.println(c);
              System.out.println(bAfter);
         public static void main(String args[])
              new TestNarw();
               the SURPRISE on the code above is that the output is :
    -100
    -100
    and when i change the value of "bBefore" to any negative number that is to fit in a
    byte it (e.g: -10) it gives the same value for the variable "c" (character)which is ASCII "63" ="?"
    but when i test it with a suitable postive number , it works fine and the character (c) represents that number
    so how it deals with converstion from negative byte to char ?
    Thanks ...

    Q1: you can always cast between primitive types (numbers, not boolean). The only problem is you lose precision in certain directions. A long to float isn't necessarily going to change the value, but it really depends on the long value. If it's out of range of float, it'll basically be wrapped around to the negative side. (at least that's what long to int would do, not sure if float or double behave different in that regard).
    Q2: The value -100 converted to a char would probably be 65436, which prints as "?" because DOS can't print that character. Then when you cast back, 65436 is out of range for a byte, so it rolls back around to -100.
    Try this:
    byte b = 127;
    System.out.println(b);
    System.out.println((byte)b+1);
    System.out.println((byte)0xFF); // 255 in hex
    It'll print 127, then -128, then -1. When you go out of range, it just wraps around. For this reason, you often have to be carefull what size you store things as.

  • Convert/Cast Single to double inaccurate.

    Whilst I have read some background on floating opint numbers not being able to accurately store numbers such as 0.1, I am not clear why converting from single to double is so inaccurate.
    Converting a single 0.1 to a double 0.1 yeilds
    0.10000000149011600
    But 0.1 can be represented in a double more accurately, even if not perfectly as
    0.10000000000000000
    This stems from the single representation of 0.1 actually equating to 0.10000000149011600 in binary.
    However, we know that the single has a particular level of precision.
    I would like a conersion function that converts single 0.10000000 to double 0.1000000000000000.
    I can appreciate that the standard conversion functions would need to still exist as real numbers for engineering would suffer less overall inaccuracies with the existing rounding functions.
    One other question:
    Can the convertsion be affected by the OS/framework/hardware or will it be consistent on different machines?  Are there any settings that can change the conversion behaviour?

    There is no reason that we should explicitly convert a single precision number to a double precision number using some function as a simple assignment would do the same. Please review the following code:
    float x = 10.5367f;
    double a = Convert.ToDouble(x);
    double b = (double)x;
    double c = x; //same as conversion or casting
    In the previous example, when x is declared as float, the memory space that is allocated is sufficient to hold the value of x as float along with precision. Now when we assign the value to some double variable (by conversion/casting/direct assignment), all
    what happens is,
    1. the space for the double variable is allocated
    2. the value is copied from single the single variable to double variable.
    Now obviously, the value of the single variable does not span as much memory space as the double variable. So when copied to double the remaining memory space of the double variable is still filled up with garbage data. The actual value of the single variable
    is still preserved upto the range of single precision.
    So frankly speaking, there is no such straightforward way that can be used to fill the garbage digits with 0s.
    I personally recommend that you use "decimal" instead of "double" if any such conversion is required.
    Thanks.

  • In your experience

    I was going to post the link here but then I would be advertising and that is not my idea, so I decided to just post the content of the course.
    In your experience would you say that this is a good course for me to start with:? I do not have any back ground in programming but I am king to learn.
    In total this is a 5 day course based in London.
    Course Content
    Module 1 - Getting Started
    Origins of the language and its key features
    Describing the Java Runtime Environment and the components of the Java 2 Standard Edition (J2SE)
    Comparing local and distributed Java applications and associated security features
    Writing, compiling and running a simple Java application
    Using documentation for the J2SE class libraries
    Module 2 - Object-Oriented Programming
    Defining classes, objects, variables and methods
    Building an object and understanding object references and garbage collection
    Using constructor methods to initialise objects
    Using package and import statements to access the J2SE class libraries
    Applying access modifiers to object members
    Module 3 - Keywords and primitive types
    Recognizing Java Keywords
    Listing the eight primitive types
    Understanding conversion and casting of primitive types
    Recognizing and using Java operators
    Module 4 - Flow Control
    Iteration using for loops, while loops and do-while loops
    Building nested loops, and breaking out of a loop
    Using labels and the continue keyword
    Building alternative execution paths with a switch block
    Module 5 - Arrays
    Declaring, creating and initialising arrays of primitive types
    Building arrays of objects
    Building multi dimensional arrays
    Passing arguments into the main method of a command line application
    Building an application that uses arrays, method calls and iterative loops
    Module 6 - Object-Oriented design
    Describing the three pillars of object-oriented design (Inheritance, Polymorphism and Encapsulation)
    Inheritance and building a derived class
    Understanding a class hierarchy and the methods of the Object class
    Describing polymorphism and building an overriding method
    Enforcing polymorphism with interfaces and abstract classes
    Encapsulation and its advantages in producing maintainable code
    Module 7 - Further Class Features
    Building overloaded methods and constructors
    Declaring and using static variables and methods
    Declaring and using final classes, variables and methods
    Module 8 - Exceptions
    Defining exceptions and building code to handle a runtime exception
    Explaining the Exception class hierarchy and categories of exceptions
    Declaring methods that may throw exceptions
    Using the throw keyword forward an exception
    Building a user-defined Exception class
    Module 9 - Collections
    Categorising collections classes by the interfaces that they implement
    Using Sets, Lists and Maps to store collections of objects at runtime
    Building an iterator to access the objects in a Set
    Adding key - value pairs to a HashMap
    Using object reference casting when assigning references from a collection
    Module 10 - Building a Graphical User Interface (GUI)
    Describing the Swing package and its components
    Building an application window and adding components to the Content Pane
    Explaining layout managers and the rules by which they position components on a window
    Using BorderLayout, FlowLayout, GridLayout and GridBagLayout managers
    Building inner classes to handle events in a GUI , such as a menu selection
    Adding a user interface to the command line application built during previous modules
    Module 11 - Applets
    Comparing GUI applications to applets
    Explaining applet methods that are called by the browser
    Writing HTML code to display an applet within a web page
    Executing a Java 2 applet on any browser by automatically downloading the Java Runtime Environment
    Using the paint method to draw an image on a component
    Module 12 - Threads
    Creating threads to enable concurrent execution of multiple tasks
    Declaring synchronized code to prevent simultaneous access to a method by more than one thread
    Moving threads between states using the wait and notify methods
    Using a shared object to communicate between threads
    Module 13 - I/O Streams
    Interrogating the local file system
    Using Character Streams to read and write to a text file
    Understanding processing streams and linking them to sink streams
    Building byte streams to send and receive binary data
    Using object serialization to give persistence to objects
    Module 14 - Networking
    Distinguishing between Transmission Control Protocol (TCP) and User Datagram Protocol (UDP)
    Translating between character streams and byte streams
    Building a Server application that listens on a specified port
    Building a Client application that establishes a connection with the Server and sends some text
    Following by the second part :
    Course Content
    Module 1 - Java Database Connectivity (JDBC)
    Describing the JDBC architecture
    JDBC driver categories, including the JDBC-ODBC bridge and Type 4 drivers
    Establishing a database connection
    Creating and updating a database table
    Using batch updates and prepared statements
    Querying a database and extracting metadata
    Using record locking and committing or rolling back a transaction
    Handling SQL exceptions and obtaining the SQL state for single and chained exceptions
    Module 2- The Java API for XML Processing (JAXP)
    Explaining XML Document structure, namespaces and Document Type Definitions
    Parsing XML data with the Simple API for XML Parsing (SAX)
    Parsing XML data with the Document Object Model (DOM) and navigating through the DOM
    Writing code to read an XML file into a database table
    Reading a ResultSet from an SQL query into an XML DOM
    Transforming an XML document using an XSL stylesheet
    Module 3- Adding a Swing User Interface to the database application
    Defining Model-View-Controller architecture
    Using UML class diagrams to describe the types of objects in an application and their static relationships
    Building a GUI using ?drag and drop? and understanding the underlying code
    Using a TableModel object to parse and display XML data in a JTable
    Building a client-side Controller object to interact with the database
    Displaying input dialogs and message dialogs
    Module 4- Remote Method Invocation
    Describing the RMI architecture and the alternatives to RMI
    Listing the steps involved in developing applications using RMI
    Defining and implementing a remote interface
    Generating stubs, starting the registry and registering objects
    Looking up a remote object using the RMI protocol
    Dynamically loading and instantiating class files from a web server
    Implementing security with a policy file
    Creating worker threads for time-consuming tasks
    Module 5- Servlets and Web containers
    Explaining the purpose and structure of a Servlet, and deploying a Servlet in a Web Container
    Writing a Servlet that will return XML data from an SQL query sent over HTTP from a Web client.
    Adding code to enable the Servlet to be accessed from the Swing application client built during previous modules
    [ Note that, while Servlets are part of the Java 2 Enterprise Edition, this module may be useful to delegates who intend to deploy Java applications in a Web Container provided by their Internet Service Provider ]
    Many thanks for any comment reagarding my query.
    Kind Regards,

    There's no game development!

  • Convery byte[] into a object

    i have a byte[] which I have got from DB. I want to convert it into a object before returning it from a method. There is a wraaper class for byte i.e. Byte. But I am not sure tha how to convert a byte[] into an Object.
    Thanks!!

    georgexu316 wrote:
    corlettk wrote:
    georgexu316 wrote:
    If you know what you are doing, you can perform an implicit conversion by casting the byte.
    byte byteData = new byte();
    Object newObj = (Object) byteData;
    Umm.. Dude, a byte array is-an Object. In Java you don't ever need to explicitly up-cast... but (in order to actually use it as a byte array) you do have to explicitly down-cast it.
    For example:
    package forums;
    class AByteArrayIsAnObject
    public static void main(String[] args) {
    try {
    Object bytes = "Hello World!".getBytes(); // returns a reference to a newly created byte-array-object
    System.out.println( new String((byte[])bytes) );
    } catch (Exception e) {
    e.printStackTrace();
    Well, the person asked to convert it into an Object, maybe he needs it as a object to pass it through another parameter of another method. Even though byte is an extension of Object and you can use all of Object's methods, it wouldn't pass through a parameter of a method that specifies an object.Ummm... Wanna bet?
    package forums;
    class AByteArrayIsAnObjectTest
      public static void main(String[] args) {
        try {
          println(new String((byte[])getBytes("Hello World!")));
        } catch (Exception e) {
          e.printStackTrace();
      private static Object getBytes(String s) {
        return s.getBytes();
      private static void println(Object o) {
        System.out.println(String.valueOf(o));
    }

  • Parsing an Algebraic Expression

    Hi ,
    Can any body provide me an idea to parse an algebraic expression in Java.Are there any built in classes for parsing an expression and evaluating after substituting the values for variables in the expression?
    If no classes are availble,plz provide me any algorithm for doing that.
    Thanks in Advance

    Observe:
    Parsing an expression is essentially the act of converting the expression from infix notation to postfix notation. Infix requires parens and precedence to specify order of operations but post fix unambiguously specifies them by the order of the tokens
    So something like
    "a+b*c" becomes "a b c * +"
    "a*b+c" becomes "a b * c +"
    "(a+b)*c" becomes "a b + c *"
    notice that arguments (variables and numbers, the leaves of the implied expression tree) occur in the same sequence in both the infix and the postfix notation. Thus you can view the parsing as a filtering process that passes arguments directly from input to output and all the filter is doing is re-arranging the order of the operators.
    All this rearranging of operators can be done with a single stack and it is all based on this observation:
    When you saw a string like "a op1 b op2 c" you run across the token for the first operator before you have even collected its right argument. You must put that operator somewhere and a OpStack is the place to put it. You don't know whether to emit op1 until you have had a look at the next operator, op2. If op2 was higher priority than op1, then op2 gets to consume the argument b first. In that case op2 just gets added to the stack on top of op1.
    However if op2 was less than or equal in precedence to op1, well then op1 can now be flowed to the output stream and allowed to act on the b argument that is already out on the output stream.
    This means that the fundamental operation of the expression parser is the business of pushing an opertor token onto the stack, but first spewing to the output all the other operators on the stack that had a higher or equal priority. If we give this function a name like opStack.pushSpew(token) it could look something like this:
    class OpStack{
      Stack s = new Stack();
      void pushSpew(List out, Token t){
        Token tos;
        while(!s.empty() && (tos = peek()).priority >= t.priority){out.add(pop());}
        push(t);
    }Next thing to observe is that a grouper, like open and close parens, behaves in the following way. An open paren acts like a very high priority operator when pushed to the stack in that it spews nothing. The previous op is NOT allowed to eat the argument that is about to come right after the open paren. However once the open paren marks the stack, the open should be a lower priority than any real op that gets pushed onto the stack above it because it must delay going out until every real op in the group had its shot. The close paren should also act like a very low priority op. It should spew every op upto but not including the open paren that started this group.
    As a computation trick, if you set the priority of an open lowest of all, and the priority of a close just above that, and you just push the open onto the stack instead of pushSpewing it onto the stack, you will get the desired behavior. You with then pushSpew the close paren and it will dump everything from the stack to the output up to but not including the open. At this point it is easy to check the balance. If you do not have an open/close pair sitting as the top two elements on the stack then the parens (or the brackets or the braces) were not properly nested.
    We are almost done. There are post fix operators like factorial and prefix operators like minus that we need to deal with. It only makes sense to evaluate these suckers from the inside out i.e. if you had a string of prefixs on an arg
    op1 op2 op3 arg
    the only sensible order is defined by parens like this
    (op1 (op2 (op3 arg) ) )
    and in post fix that would be
    arg op3 op2 op1
    that is exactly what you would get if you just pushed each prefix op onto the stack in the order you saw them and then popped them off after you dumped out the argument.
    Post ops should also work from the inside out
    arg op1 op2
    being
    ( (arg op1) op2 )
    and you get this behavior by just dumping a post op to the output when you see it.
    There is only one special concern. What should you do if you saw, both pre ops and post ops on the same arg?
    is "op1 arg op2" done like this: "(op1 arg) op2" or "op1 (arg op2)"? Well, why should these be any different from regular diadic ops, let precdence decide. An espression like minus three factorial "-3!" should be interpreted as take the factorial of 3 and then negate it (and not the other way around!) so let the priority of factorial be greater than that of minus and just do the standard pushSpew with post ops to let them spew out any high priority pre ops before they go onto the stack, but then unlike binary ops, the post op immediately comes off the stack and goes to the output because post ops bind up right away.
    Now if you are not careful with your precedences you could get "wierd" behavior. If for example you did not assign a high priority to a factorial, you could write expressions like "3+4!" and the priority would treat that like "(3+4)!" the plus would bind tighter than the factorial. It is hard for me to imagine a language where you would want the effects of either a postfix or a prefix operator to span across multiple arguments combined by single diadic operator, but that is really up to you. You certainly could have a language where you gave a very low precedence to ~ which could mean the boolean NOT, a lower precedence than the diadic operator >= which would allow you to write "~ a >= b" which would mean "~(a>=b)"
    After all it is your language, do what you want. None the less I would advise against alowing ANY pre or post op to have a priority LESS than that of ANY diadic operator.
    Lots of talk here but to recap, the code is quite simple:
    while((t = getNextToken()) != null){
      switch (t.type()){
        case ARG:  out.add(t); break; // arguments pass straight to output
        case PRE:  stack.push(t); break; // pre ops are just pushed (binding them to the next arg)
        case OPEN: stack.push(t); break; // Opens just push, they don't spew to output
        case DI: stack.pushSpew(out,t); break; // Diadic ops do the standard pushSpew
        case POST: stack.pushSpew(out,t); out.add(stack.pop()); break; //spew and then go out
        case CLOSE: stack.pushSpew(out,t); stack.removeOCpair(); // spew all ops in group
          // and then check if you had a balancing open
    }That just about does the entire parse. If you can find the tokens in the input you can rearrange them into the output. You do need to flush the opStack when you are done with the input stream and there is a convenient trick to doing that. The trick is this. Invent an invisible Open and Close pair, invisible meaning that they never show up in any input stream, you just made them up and pretended that that expression started with an invisible OpenExp and at the end it closed with a CloseExp.
    The CloseExp at the end will act like any grouper, it will flush the stack looking for the corresponding opener. IF there was any unbalanced grouper, like say an extra unbalanced open paren somewhere in the expression, the CloseExp will spew its way down to that unbalanced paren and then fail when it discovers that it does not match the open in the call to remove the OC pair. The is a way to do error detection. Use a fictional group on the entire expression to both flush the remainder of the opStack and to do a final check for unbalanced groupers.
    In fact, while we are on the topic of error checking there is another one that is very good to include. Basically in a real expression if you ignore the parens, the progression should be an alternation between args and diadic ops, with an occasional pre or post op thrown in.
    A simple count tells you where you are. Go up to 1 when you pass an argument, go back down to zero when you see a diadic operator. You should start at zero, because there have been no arguments or ops yet. In state zero the only legal things to do are to put in a pre op or an arg. Once you have an arg out there the only legal things to do are to have a post op or a diadic op. This little state machine will tell you if and when you have got either a pair of arguments together with no op between them, or a pair of ops with no argument between them. You should start at state = 0 and you should end at state = 1 (unless you allow empty expressions) So we can beef up the error checking with a very simple addition. The guts of the parse will now look like this:
    state = 0
    stack.push(Token.OpenExp); // start off with an open of the expression
    while((t = getNextToken()) != null){
      switch (t.type()){
        case ARG:  assertStateIs(0); out.add(t); state = 1; break;
        case PRE:  assertStateIs(0); stack.push(t); break;
        case OPEN: stack.push(t); break;
        case DI: assertStateIs(1); stack.pushSpew(out,t); state =0; break;
        case POST: assertStateIs(1);stack.pushSpew(out,t); out.add(stack.pop()); break;
        case CLOSE: stack.pushSpew(out,t); stack.removeOCpair();
    stack.pushSpew(out,Token.CloseExp); stack.removeOCpair();
    assertState(1);
    return out;So - there it is, in outline form the way that you parse an expression.You build 3 classes, Token, ExpressionParser, and OpStack
    Token is just a bucket that holds a name, a type (ARG, PRE, OPEN, DI, ...) and a precedence.
    OpStack is just a wrapper for a reqular stack that will hold Tokens and allow for a pushSpew function.
    ExpressionParser is little other than a Map full of all your Tokens. This map allows the parser to map substrings, tokens, that it finds in the input like >= to actual Tokens with a capital T. It will have two main methods:
    1) the parse method which I have almost completly written for you. It takes an input string and will fill up an output list placing the Tokens in post fix order, which is your parse tree.
    2) the routine getNextToken which will walk the input string, skipping white space when appropriate, looking for names, numbers, and operators and building each chunk that it finds into a Token.
    One last complexity note. If you want to allow functional notation like sqrt(3) you are using parens in a fundamentally different way than was described above (ditto when you use brackets to represent array indexing like x[5]) the fundamentally different thing that you are doing is that you are allowing an argument (a name) like "sqrt" to sit right next to another argument like "3" with no binary op in between. You are using an "implied" binary op at that point. You have saved the user from typing "sqrt FUNCTIONCALL (3)" or "x ARRAYINDEX 5"
    I will leave it as an exercise to the reader to see how you make a small modification to the OPEN case to detect and deal with an implied operation. Don't forget that you must tell the state error checker what you are doing.
    And now that I have shown you how fundamentally simple it is to build an expression parser let me comment on why you do not find a standard library routine for doing this.
    The primary reason is that there is no such thing as a "standard" math expression. Parsing is based on a language and there is no one language. Are you going to allow hex numbers in your expressions? How about scientific notation? Is = equality or assignment? Do you allow functional notation? Array indexing? Multi-dimensional array (like x[2,3])? How about string constants like "foobar"? How do you embed quotes in your quoted strings? Are you allowing comments, block comments, statements, code, Lisp expressions, complex numbers, implicit type conversion, type casting? At what point does it stop being a simple expression and start being a full computer language?
    Furthermore, most of the work you will quickly see if you use what I have suggested to build an expression parser, it how to give your user feedback that the expression that he typed had problems and where. There is no stardard UI for error feedback in things that don't parse correctly. Are you just going to dump cryptic strings to the console or are you going to highlight something in a text box somewhere?
    All the work turns out to be that of defining your language and determining your set of tokens and what precedence you will employ. Once you get that all worked out, parsing the expressions only takes the ten or fifteen lines of code that I outlined.
    And look, it only took several thousands of words to explain why it only takes about 15 lines of code to parse expressions once you have decided upon your language and written your tokenizer.
    Enjoy

  • Cannot implicitly convert type 'System.Data.SqlClient.SqlDataReader' to 'Microsoft.ReportingServices.DataProcessing.IDataReader'. An explicit conversion exists (are you missing a cast?)

    Cannot implicitly convert type 'System.Data.SqlClient.SqlDataReader' to 'Microsoft.ReportingServices.DataProcessing.IDataReader'. An explicit conversion exists (are you missing a cast?)
    I am getting the above error in c#. Please help me. Thanks in advance
    public IDataReader ExecuteReader(CommandBehavior behavior)
    string query = "select * from Sales.Store";
    SqlConnection readerconn = new SqlConnection("Data Source=localhost;Initial Catalog=AdventureWorks2000;Integrated Security=SSPI");
    SqlCommand readercmd = new SqlCommand(query);
    try
    readerconn.Open();
    readercmd = readerconn.CreateCommand();
    readercmd.CommandText = query;
    readercmd.CommandType = System.Data.CommandType.Text;
    SqlDataReader TestReader = readercmd.ExecuteReader();
    return TestReader; //Getting error at this line
    readerconn.Close();
    catch (Exception e)
    throw new Exception(e.Message);

    Hi,
    Please firstly take a look at the documentation:
    IDbCommand.ExecuteReader
    Method
    Users do not create an   instance of a
    DataReader   class directly. Instead, they obtain the
    DataReader   through the
    ExecuteReader   method of the Command   object. Therefore, you should mark
    DataReader   constructors as internal.
    You need to use this method to get the IDataReader object, all the IDbCommand and IDataReader are in the Microsoft.ReportingServices.DataProcessing namespace. There's another IDataReader object which is in System.Data namespace, but they're actually two different
    objects, that's why you got the exception.
    For how to properly implement this Microsoft.ReportingServices.DataProcessing.IDataReader, please check this documentation:
    Implementing a DataReader Class for a Data Processing Extension
    It also provides code samples there.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Question about compile-time legality rules for cast conversion

    Hi, In the rules which explain compile-time legality for cast conversion, it is often mentioned the following scenario in the cast conversion of a compile-time type S to a compile-time type T:
    if S is a class type then:
    if T is a class type then either |S| <: |T| or |T| <: |S| or a compile time error occurs. Furthermore, if there exist a supertype X of T and a supertype Y of S such that X and Y are provably distinct parameterized types and that the erasures of X and Y are the same, a compile-time error occurs.
    As regards the quote in bold, I imagine the following scenario:
    1) S <: T and extends Y
    2) Y<T1...Tn>
    3) X<T1..Tn>
    4) T extends X
    Does the above represents a supertype X of T and a supertype Y of S such that X and Y are provenly distinct parameterized types? If that holds, what does it mean that the erasure of X and Y is the same?

    Declarative programing has all but gone the way of
    the doe doe because...
    1: It is not flexible (It is extremely difficult to
    change a complex system in a predetermined way)isn't this the "expert system" model?
    2: It lengthens the development cycle (see item 1)
    3: It normally forces the developer to add many
    things to there code to get things to work, that have
    nothing to do with the intent of the code.more things? the declarations or the declaration processing?
    In its defense (I like a declarative model but, do
    not like being forced into one)...not advocating a forced change in Java
    1: It increases code safety.
    2: It can shorten the development cycle, in certain
    circumstances (especially if it is not overused),
    because it can greatly increase the readability of
    code.
    3: It follows many best practices (although this is
    also possible in a Non-Declarative model).as for best practices what I'd like to see are declarative design patterns, Adapter, Singleton, Factory, Delegate, Strategy, Interpreter, Proxy, Visitor
    too often the design intent is lost in an implementation or design details can only be deduced by class/field/method names, comments, and accompanying docs
    So, if everyone had unlimited time, and an unlimited
    budget, yes declaritive is the way to go. Since that
    is not the case, we filtered out 99% of what it gave
    us, made sure the stuff that was getting in the way
    was removed, and what do you have???
    You guessed it OOA&D.
    Now having said that should we be more declarative? I
    think so, but I will tell you now, REQUIRING
    declarative elements in code is a sure fire way to
    get the majority of development groups to drop the
    language (and I think Java as it stands currently CAN
    be declarative, so if you have one of those unlimited
    budgets, go for it!).no need to require it
    I believe given good (reusable) declarative options, on top of OOP, will become the chosen approach
    reusable design declarations would lessen overall cost and increase readability

  • Casting or Conversion?

    Hello,
    Suppose I have the following scenario:
    class A { ... }
    class B extends A { ... }
    class C
         public C(A a) { ... }
         public C (B b)
               this((A)b); //Casting or conversion???
    }My question is what exactly happens in the line with the comment: Casting or conversion? When does Java do each of them?
    Thanks.

    Thanks for all your replies. Now suppose I want to
    alter an object of type B to an object of type A and
    not cast it. How can I do that?Java has reference semantics for objects only. This means that when an object gets assigned to a variable it's not the object value that's assigned. The object values is "on the heap" and stays there. What's get assigned is always a reference to the object.
    In C++ on the other hand you have both reference and value semantics available for objects. Now if you assigned a B object to an A variable BY VALUE then the B portion of the object will be "sliced off". The B object will get altered and become an A object. The B'ishness gets lost in the process.
    This kind of "slicing" assignments can never happen in Java because it has reference semantics for objects only. Only references get assigned.

  • Rounding Differences between TSQL Cast and Data Conversion component

    This is using SSIS 2012.  We are using an Ole Db Connection manager using the Microsoft.ACE.OLEDB.12.0 provider.
    I have an Access database (accdb). It has several columns that are coming into SSIS as real data types.  One column has a value of 68.8335558900872.
    In the past we used the Data Conversion to convert from real to numeric 18, 6.  The result was 68.833555.  Rather than rounding on the last decimal place, it is returning the floor at six decimal places.
    We have converted the process to load the data into a real data type column and then use a view to cast the value to a Decimal 18,6 (CAST (Col1 as Decimal(18,6))).  We then load the data into a decimal 18,6 column.  The result is 68.833556, which
    is the rounded version of the real value.
    Personally I prefer the rounded version rather than the truncated version.
    I am trying to explain to explain to the QA people why the revised process is producing different results and thus I want to know if these are known behaviors for TSQL Cast and the Data Conversion component.
    Russel Loski, MCT, MCSE Data Platform/Business Intelligence. Twitter: @sqlmovers; blog: www.sqlmovers.com

    I think such a post is more suitable for an MS Connect bugs section as I see it a defect. And it seems no floor, but simply cutting off. Try in .Net when you convert, does it work the same? Data Conversion is a wrapper around the .net
    Arthur My Blog

  • Casting and radio select : conversion error

    I'd like to display radio options differently, regarding of their type.
    For example I have an OpenOption class which extends Option. So when I display it I'd like to add an input text box if the user select an open option :
                             <h:selectOneRadio value="#{q.answer}">
                                 <s:selectItems value="#{q.target.options}" var="opt" label="#{opt.text}" />                       
                                 <a:support event="onchange" reRender="pnlOpenText"/>
                             </h:selectOneRadio>                         
                             <a:outputPanel id="pnlOpenText">
                                     <h:panelGroup id="innerPnlOpenText" rendered="#{q.answer.class.simpleName eq 'OpenOption'}">
                                       <h:outputText value="#{q.answer.freeTextLabel}"/>&#160;
                                       <h:inputText value="#{q.freeText}" size="50"/>                                   </h:panelGroup>
                             </a:outputPanel>I use the following EL expression to test the type of the selected option :
    #{q.answer.class.simpleName eq 'OpenOption'}It works well BUT if I select the open option and refresh the page, the RadioRenderer fail when trying to convert ALL the options into OpenOption :
    Cannot convert Option[ id=null, text=Q1, rank=0 ] of type class Option to class OpenOptionFor the time being I see only one solution : put a type attribute in my Option class ... I believe this is not the best design.
    Is there any other workaround ?
    Would it be possible to have a renderer which doesnt infer the options type from the selected option but individually for each option ? I don't know anything about the spec ...
    Thanks,
    Bruno

    Java is case sensitive language after all , plus beans getters and setters naming rules :)
    SetConfirmClaim
    must be
    setConfirmClaim
    It raises a question though whether more exact error reporting is achievable , not just "Conversion error has occured".

  • Blue Cast on CR2 conversion to DNG

    I'm wondering if anyone can explain why CR2 files from a Canon 1D Mark II exhibit a strong blue cast when converted to DNG using the standalone Adobe DNG converter version 5.5.0.97 or Lightroom 2.5. (see examples below).
    Here's the test I conducted:  I first shot a JPEG image of an X-Rite grey card using Auto White Balance then used it to set a custom white balance in my 1D Mark II.  I then repeated the same test using a RAW file and in both instances the camera functions as expected.  However, when I converted the CR2 files to DNG they took on a strong blueish cast.
    For comparison purposes I then did the same test using a Canon 5D and those CR2 files do not show the blueish cast when converted to DNG.
    Here's a shot of the thumbnails as they appear in BreezeBrowser Pro (thumbnail color management enabled).  They look the same in Adobe Bridge too.  The first six thumbnails are from the Canon 1D Mark II and the second six are from the Canon 5D.
    Thanks for any help.

    The only thing wrong with your DNG is that the embedded preview was created with the WB set to something like Tungsten while the DNG metadata parameters say As Shot for the WB.  How it got that way you're going to have to figure that out.  I say this because both LR and Br show a brief blue flash when the image is initially imported, then it corrects to the As Shot WB.  This means the preview is bad but the parameters are ok.
    I'm going to guess you had the DNG open in LR and clicked or synced it to something like Tungsten from some other image, and then created the DNG with the preview, then corrected the WB in LR and then updated the DNG metadata without updating the preview--perhaps by having the Auto XMP writing turned on.
    I'd suggest removing the CR2 (and any associated DNGs) from the library, deleting any XMP, and starting over by importing the CR2 with As Shot parameters and convert directoy to DNG from W/in LR and see if you can make it happen, again.  If you figure it out, then tell us.  If you can't figure it out, then don't worry.  The CR2 and the DNG are ok and you can use them for creating your color profile with the passport software which ignores any edits you make to the DNG anyway.  Trying it with my Passport software shows a non-blue DNG with the green rectangles over the various squares, so the DNG, itself, is fine, just the preview is wrong.

  • Conversion Casting Problem here....

    Hi,
    I can't find this on google.
    I need to go from a Double to an int.
    Notice its capitol D, cause its a "Double".
    Just need a quick response. Thanks.
    And yes I searched on google :(

    [url http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Double.html#intValue()]Double.intValue

Maybe you are looking for

  • Hi all problem with sql server 2008 in sap b1 2005 PL38,42

    Hello Sir, We are also facing this problem. Our client has purchased SQL 2008 & we have installed SAP B1 PL 05 & also we have to upgrade it to PL 26 atleast for installing TDS Add on 4.8 so that Project runs smoothly. Can u specify the status? i.e. a

  • How to update multiple rows

    i have one array of string score1[] and i want to update those value in table how the query should be......... i thought it work as like for insert query but following is not working PreparedStatement ps = con.prepareStatement("update class_test_scor

  • Is photoshop element 10 compatable with windows 8

    is Photoshop element 10 compatible with windows 8 

  • Re: stock is not in reality but shows at warehouse level

    Dear Friends, i have a problem. Mateiral is not avialble in inventory but it shows in warehouse at interim storage area (902,922 & 999) as the material not exists in reality and shows in the above interim storage area. how can i clear the stock from

  • Update statement with Case syntax

    I want to put case statement in an update statement using Oracle 10g I'm getting a syntax error on the last line Ora-00933: SQL command not properly ended Help please UPDATE EMP a SET EMP.TYPE = CASE WHEN 'Y' = 'A' THEN 'DIV' WHEN 'Y' = '1' THEN 'DEF