Search Results

Search found 61 results on 3 pages for 'coercion'.

Page 1/3 | 1 2 3  | Next Page >

  • which one of these is an example of coercion

    - by user1890210
    I have been pondering a multiple choice question on coercion. One of the 4 examples a,b,c or d is an example of coercion. I narrowed it down to A or B. But I am having a problem choosing between the two. Cane someone please explain why one is coercion and one isn't. A) string s="tomat"; char c='o'; s=s+c; I thought A could be correct because we have two different types, character and string, being added. Meaning that c is promoted to string, hence coercion. B) double x=1.0; double y=2.0; int i=(int)(x+y); I also thought B was the correct answer because the double (x+y) is being turned into a int to be placed in i. But I thought this could be wrong because its being done actively through use of (int) rather than passively such as "int i = x + y" I'll list the other two options, even though I believe that neither one is the correct answer C) char A=0x20; A = A << 1 | 0x01; cout << A << endl; D) double x=1.0; double y=x+1; return 0; I'm not just looking for an answer, but an explanation. I have read tons of things on coercion and A and B both look like the right answer. So why is one correct and the other not.

    Read the article

  • A simple question about type coercion in C++

    - by David
    Given a function prototype, and a type definition: int my_function(unsigned short x); typedef unsigned short blatherskite; Is the following situation defined by standard: int main(int argc, char** argv) { int result; blatherskite b; b=3; result = my_function(b); } Do I get type coercion predictably via the function prototype?

    Read the article

  • 1067: Implicit coercion of a value of type theplayclass to an unrelated type main

    - by Minelava
    I need help because I want to create a gameover screen that display score. However, there's an error that prevent me from transferring the score from theplayclass.as to thegameoverclass.as. Are there ways to pass a value to another movieclip without causing any errors. I refer the source code from this website : http://www.emanueleferonato.com/2008/12/17/designing-the-structure-of-a-flash-game-as3-version/ Here's the error C:\Users\xxx\Downloads\Migrate\test\theplayclass.as, Line 54, Column 41 1067: Implicit coercion of a value of type theplayclass to an unrelated type main. main.as package { import flash.display.MovieClip; import flash.events.Event; public class main extends MovieClip { public var playClass:theplayclass; public var gameOverClass:thegameoverclass; public function main() { showWin(); } public function showWin() { playClass = new theplayclass(this); addChild(playClass); } public function showGameOver() { gameOverClass = new thegameoverclass(this); addChild(gameOverClass); removeChild(playClass); playClass = null; } } } theplayclass.as package { import flash.display.MovieClip; import flash.events.*; public class theplayclass extends MovieClip { private var mainClass:main; var gameScore:Number; var gameOverScore:thegameoverclass; public function theplayclass(passedClass:main) { mainClass = passedClass; scoreText.text ="0"; gameScore = 0; win.addEventListener(MouseEvent.CLICK, showwinFunction); next.addEventListener(MouseEvent.CLICK, showgameoverFunction); addEventListener(Event.ADDED_TO_STAGE, addToStage); addEventListener(Event.ENTER_FRAME, changeScore); } public function addToStage(e:Event):void { this.x = 0; this.y = 0; } private function showwinFunction(e:MouseEvent):void { gameScore+=50; } private function changeScore(e:Event):void { scoreText.text =""+gameScore; } public function showgameoverFunction(e:MouseEvent) { mainClass.showGameOver(); gameOverScore = new thegameoverclass(this); gameOverScore.setTextScore(gameScore); } } } thegameoverclass.as package { import flash.display.MovieClip; import flash.events.MouseEvent; import flash.events.*; public class thegameoverclass extends MovieClip { var mainClass:main; var scorePoints:Number; public function thegameoverclass(passedClass:main) { mainClass = passedClass; finalScore.text = "test"; } public function setTextScore(textToSet:Number) { finalScore.text = ""+scorePoints; } } }

    Read the article

  • F# return type coercion

    - by Alex
    Hi, In F# I have a function that returns System.Linq.Expression instances: and System.Object with member this.ToExpression() = match this with | :? System.Int32 -> Expression.Constant(this) :> Expression | :? System.Boolean -> Expression.Constant(this) :> Expression | :? Tml.Runtime.Seq as s -> s.ToExpression() | _ -> failwith "bad expression" If I omit the type coercions on the return values F# will infer the return type of the function to ConstantExpression. My first thought was to explicitly mark the return type as being : #Expression, but that didn't work. Is there a more elegant way of doing this that doesn't involve manually casting return types to the most generic type? Thanks.

    Read the article

  • A follow up on type coercion in C++, as it may be construed by type conversion

    - by David
    This is a follow up to my previous question. Consider that I write a function with the following prototype: int a_function(Foo val); Where foo is believed to be a type defined unsigned int. This is unfortunately not verifiable for lack of documentation. So, someone comes along and uses a_function, but calls it with an unsigned int as an argument. Here the story takes a turn. Foo turns out to actually be a class, which can take an unsigned int as a single argument of unsigned int in an explicit constructor. Is it a standard and reliable behavior for the compiler to render the function call by doing a type conversion on the argument. I.e. is the compiler supposed to recognize the mismatch and insert the constructor? Or should I get a compile time error reporting the type mismatch.

    Read the article

  • How can I determine if an object or reference has a valid string coercion?

    - by Ether
    I've run into a situation (while logging various data changes) where I need to determine if a reference has a valid string coercion (e.g. can properly be printed into a log or stored in a database). There isn't anything in Scalar::Util to do this, so I have cobbled together something using other methods in that library: use strict; use warnings; use Scalar::Util qw(reftype refaddr); sub has_string_coercion { my $value = shift; my $as_string = "$value"; my $ref = ref $value; my $reftype = reftype $value; my $refaddr = sprintf "0x%x", refaddr $value; if ($ref eq $reftype) { # base-type references stringify as REF(0xADDR) return $as_string !~ /^${ref}\(${refaddr}\)$/; } else { # blessed objects stringify as REF=REFTYPE(0xADDR) return $as_string !~ /^${ref}=${reftype}\(${refaddr}\)$/; } } # Example: use DateTime; my $ref1 = DateTime->now; my $ref2 = \'foo'; print "DateTime has coercion: " . has_string_coercion($ref1) . "\n\n"; print "scalar ref has coercion: " . has_string_coercion($ref2) . "\n"; However, I suspect there might be a better way of determining this by inspecting the guts of the variable in some way. How can this be done better?

    Read the article

  • In Ruby, can the coerce() method know what operator it is that requires the help to coerce?

    - by Jian Lin
    In Ruby, it seems that a lot of coerce() help can be done by def coerce(something) [self, something] end that's is, when 3 + rational is needed, Fixnum 3 doesn't know how to handle adding a Rational, so it asks Rational#coerce for help by calling rational.coerce(3), and this coerce instance method will tell the caller: # I know how to handle rational + something, so I will return you the following: [self, something] # so that now you can invoke + on me, and I will deal with Fixnum to get an answer So what if most operators can use this method, but not when it is (a - b) != (b - a) situation? Can coerce() know which operator it is, and just handle those special cases, while just using the simple [self, something] to handle all the other cases where (a op b) == (b op a) ? (op is the operator).

    Read the article

  • In Ruby, how does coerce() actually work?

    - by Jian Lin
    It is said that when we have a class Point and knows how to perform point * 3 like the following: class Point def initialize(x,y) @x, @y = x, y end def *(c) Point.new(@x * c, @y * c) end end point = Point.new(1,2) p point p point * 3 Output: #<Point:0x336094 @x=1, @y=2> #<Point:0x335fa4 @x=3, @y=6> but then, 3 * point is not understood: Point can't be coerced into Fixnum (TypeError) So we need to further define an instance method coerce: class Point def coerce(something) [self, something] end end p 3 * point Output: #<Point:0x3c45a88 @x=3, @y=6> So it is said that 3 * point is the same as 3.*(point) that is, the instance method * takes an argument point and invoke on the object 3. Now, since this method * doesn't know how to multiply a point, so point.coerce(3) will be called, and get back an array: [point, 3] and then * is once again applied to it, is that true? point * 3 which is the same as point.*(3) and now, this is understood and we now have a new Point object, as performed by the instance method * of the Point class. The question is: 1) who invokes point.coerce(3) ? Is it Ruby automatically, or is it some code inside of * method of Fixnum by catching an exception? Or is it by case statement that when it doesn't know one of the known types, then call coerce? 2) Does coerce always need to return an array of 2 elements? Can it be no array? Or can it be an array of 3 elements? 3) And is the rule that, the original operator (or method) * will then be invoked on element 0, with the argument of element 1? (element 0 and element 1 are the two elements in that array returned by coerce) Who does it? Is it done by Ruby or is it done by code in Fixnum? If it is done by code in Fixnum, then it is a "convention" that everybody follows when doing a coerce? So could it be the code in * of Fixnum do something like this: if (something.typeof? ...) else if ... # other type else if ... # other type else # if it is not a type I know array = something.coerce(self) return array[0].*(array[1]) end

    Read the article

  • Problem with type coercion and string concatenation in JavaScript in Greasemonkey script on Firefox

    - by Yi Jiang
    I'm creating a GreaseMonkey script to improve the user interface of the 10k tools Stack Overflow uses. I have encountered an unreproducible and frankly bizarre problem that has confounded me and the others in the JavaScript room on SO Chat. We have yet to find the cause after several lengthy debugging sessions. The problematic script can be found here. Source - Install The problem occurs at line 85, the line after the 'vodoo' comment: return (t + ' (' + +(+f.offensive + +f.spam) + ')'); It might look a little weird, but the + in front of the two variables and the inner bracket is for type coercion, the inner middle + is for addition, and the other ones are for concatenation. Nothing special, but observant reader might note that type coercion on the inner bracket is unnecessary, since both are already type coerced to numbers, and type coercing result is useless when they get concatenated into a string anyway. Not so! Removing the + breaks the script, causing f.offensive and f.spam to be concatenated instead of added together. Adding further console.log only makes things more confusing: console.log(f.offensive + f.spam); // 50 console.log('' + (+f.offensive + +f.spam)); // 5, but returning this yields 50 somehow console.log('' + (+f.offensive + +f.spam) + ''); // 50 Source: http://chat.stackoverflow.com/transcript/message/203261#203261 The problem is that this is unreproducible - running scripts like console.log('a' + (+'3' + +'1') + 'b'); in the Firebug console yields the correct result, as does (function(){ return 'a' + (+'3' + +'1') + 'b'; })(); Even pulling out large chunks of the code and running them in the console does not reproduce this bug: $('.post-menu a[id^=flag-post-]').each(function(){ var f = {offensive: '4', spam: '1'}; if(f){ $(this).text(function(i, t){ // Vodoo - please do not remove the '+' in front of the inner bracket return (t + ' (' + +(+f.offensive + +f.spam) + ')'); }); } }); Tim Stone in the chatroom has reproduction instruction for those who are below 10k. This bug only appears in Firefox - Chrome does not appear to exhibit this problem, leading me to believe that this may be a problem with either Firefox's JavaScript engine, or the Greasemonkey add-on. Am I right? I can be found in the JavaScript room if you want more detail and/or want to discuss this.

    Read the article

  • ActionScript: Type coercion problem with BlazeDS/AMF and class interfaces

    - by mike
    Hi, I've got a problem with type coercion in a Java/Hibernate/BlazeDS/Flex-Setup. First of all, my classes look like this: --- JAVA --- Interface I (Abstract) Class A implements I Class B extends A --- ActionScript --- Interface I Class A implements I Class B extends A I got RemoteClass-Meta-Tags in all ActionScript-Classes/Interfaces I, A and B. Package structure and Class/Interface names are exactly the same. Now here's the problem: My Java Service successfully retrieves objects of class B from my database via Hibernate. I got another class C which has a member property of interface type I, so it should be possible to assign an object of type B. But for some reason i get the following error message: TypeError: Error #1034: cannot convert Object@28b44a89 to package.name.I I checked the Java object type in the service and it is of type B and seems to be totally fine. Why can't the object of type B be assigned to a member variable of type I? This is driving me nuts. Thanks in advance.

    Read the article

  • __toString magic and type coercion

    - by TomcatExodus
    I've created a Template class for managing views and their associated data. It implements Iterator and ArrayAccess, and permits "sub-templates" for easy usage like so: <p><?php echo $template['foo']; ?></p> <?php foreach($template->post as $post): ?> <p><?php echo $post['bar']; ?></p> <?php endforeach; ?> Anyways, rather than using inline core functions, such as hash() or date(), I figured it would be useful to create a class called TemplateData, which would act as a wrapper for any data stored in the templates. This way, I can add a list of common methods for formatting, for example: echo $template['foo']->asCase('upper'); echo $template['bar']->asDate('H:i:s'); //etc.. When a value is set via $template['foo'] = 'bar'; in the controllers, the value of 'bar' is stored in it's own TemplateData object. I've used the magic __toString() so when you echo a TemplateData object, it casts to (string) and dumps it's value. However, despite the mantra controllers and views should not modify data, whenever I do something like this: $template['foo'] = 1; echo $template['foo'] + 1; //exception It dies on a Object of class TemplateData could not be converted to int; Unless I recast $template['foo'] to a string: echo ((string) $template['foo']) + 1; //outputs 2 Sort of defeats the purpose having to jump through that hoop. Are there any workarounds for this sort of behavior that exist, or should I just take this as it is, an incidental prevention of data modification in views?

    Read the article

  • Constructor Type Coercion in C++

    - by Robert Mason
    Take the following class: class mytype { double num; public: mytype(int a) { num = sqrt(a); } void print() { cout << num; } } Say there is a method which takes a mytype: void foo(mytype a) { a.print(); } Is it legal c++ (or is there a way to implement this) to call foo(4), which would (in theory) output 2? From what I can glean you can overload type casts from a user defined class, but not to. Can constructor do this in a standards-compliant manner (assuming, of course, the constructor is not explicit). Hopefully there is a way to in the end have this legal: int a; cin >> a; foo(a); Note: this is quite obviously not the actual issue, but just an example for posting purposes. I can't just overload the function because of inheritance and other program-specific issues.

    Read the article

  • Is it possible to coerce string values in xml to bool?

    - by Kugel
    Let's suppose I have xml like this one: <Server Active="No"> <Url>http://some.url</Url> </Server> C# class looks like this: public class Server { [XmlAttribute()] public string Active { get; set; } public string Url { get; set; } } Is it possible to change Active property to type bool and have XmlSerializer coerce "Yes" "No" to bool values? Edit: Xml is received, I cannot change it. So, in fact, i'm interested in deserialization only.

    Read the article

  • How to coerce type of ActiveRecord attribute returned by :select phrase on joined table?

    - by tribalvibes
    Having trouble with AR 2.3.5, e.g.: users = User.all( :select => "u.id, c.user_id", :from => "users u, connections c", :conditions => ... ) Returns, e.g.: => [#<User id: 1000>] >> users.first.attributes => {"id"=>1000, "user_id"=>"1000"} Note that AR returns the id of the model searched as numeric but the selected user_id of the joined model as a String, although both are int(11) in the database schema. How could I better form this type of query to select columns of tables backing multiple models and retrieving their natural type rather than String ? Seems like AR is punting on this somewhere. How could I coerce the returned types at AR load time and not have to tack .to_i (etc.) onto every post-hoc access?

    Read the article

  • Web service actionscript error

    - by H P
    Hello, I am new to Flex and needed some help setting up Web service client. I have a web service of method: public String printEchoStr(String str); I am facing problem while creating action script to call this service. I am getting error: 1067: Implicit coercion of a value of type String to an unrelated type generated.webservices:PrintEcho. I am not sure if this is the correct way. Thanks, -H <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:srv="generated.webservices.*" creationComplete="initFunc()"> <mx:Script> <![CDATA[ import generated.webservices.EchoService; import generated.webservices.PrintEchoStrResultEvent; import generated.webservices.PrintEchoResultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.events.FaultEvent; import mx.controls.Alert; import generated.webservices.PrintEchoStr; import generated.webservices.PrintEcho; public var myService:EchoService = new EchoService(); private function initFunc():void{ myService.addprintEchoStrEventListener(argPrintEchoStr); /*-------------- 1067: Implicit coercion of a value of type String to an unrelated type generated.webservices:PrintEcho. at line below ----------------*/ myService.printEchoStr(textAreaPrintEchoStr.text); myService.addEventListener(FaultEvent.FAULT,myServices_faultHandler); } public function argPrintEchoStr(event:PrintEchoStrResultEvent):void{ trace(event.result); } private function myServices_faultHandler(event:FaultEvent):void { Alert.show(event.fault.faultString,"error with WebServices"); } ]]> </mx:Script> <mx:TextArea id ="textAreaPrintEchoStr" x="81" y="125"/> </mx:Application>

    Read the article

  • Returning status code where one of many errors could have occured

    - by yttriuszzerbus
    I'm developing a PHP login component which includes functions to manipulate the User object, such as $User->changePassword(string $old, string $new) What I need some advice with is how to return a status, as the function can either succeed (no further information needs to be given) or fail (and the calling code needs to know why, for example incorrect password, database problem etc.) I've come up with the following ideas: Unix-style: return 0 on success, another code on failure. This doesn't seem particularly common in PHP and the language's type-coercion messes with this (a function returning FALSE on success?) This seems to be the best I can think of. Throw an exception on error. PHP's exception support is limited, and this will make life harder for anybody trying to use the functions. Return an array, containing a boolean for "success" or not, and a string or an int for "failure status" if applicable. None of these seem particularly appealing, does anyone have any advice or better ideas?

    Read the article

  • How to test if a gawk string contain a number?

    - by Tim Menzies
    In gawk I know two ways to test if a string contains a number. Which is best? Method one: using regular expressions: function method1(x) { return x ~ /^[+-]?([0-9]+[.]?[0-9]*|[.][0-9]+)([eE][+-]?[0-9]+)?$/ } Method two: the coercion trick (simpler): function method2(x) { return (x != "") && (x+0 == x) } Is there any reason to favor the more complex method1 over the simpler method2?

    Read the article

  • AS3: How to move a MovieClip to front?

    - by Oden
    Hey, I have a problem with moving a MovieClip to front in actionscript3. The main problem is, everytime I try to move it to front, using setChildIndex() I get an error message witch tells me, that the movieclip (that I named my_tofront) cannot converted to a flash.display.DisplayObject full error message: TypeError: Error #1034: Type Coercion failed: cannot convert my_tofront$ to flash.display.DisplayObject. Why is this happening, and whats the solution for this problem?

    Read the article

  • Flash type casting gone wrong

    - by Malfist
    Sorry, I'm new to flash I have this line of code: BaseEntry( _entryList[i] ).topTeamName = ((Team)(teamList.getNameAtIndex( i*2 ))).Name; and I get the error: TypeError: Error #1034: Type Coercion failed: cannot convert "[object Team]" to ncaa.Data.Team. What do I need to do to fix it?

    Read the article

  • ArrayCollection error in Flex does not accept single XML nodes - alternatives?

    - by Rees
    hello, i get this error when i retrieve an XML that only has 1 node (no repeating nodes) and i try to store in an ArrayCollection. -When I have MORE than 1 "name" nodes...i do NOT get an error. TypeError: Error #1034: Type Coercion failed: cannot convert "XXXXXX" to mx.collections.ArrayCollection. this error occurs as the line of code: myList= e.result.list.name; Why can't ArrayCollection work with a single node? I'm using this ArrayCollection as a dataprovider for a Component -is there an alternative I can use that will take BOTH single and repeating nodes as well as work as a dataprovider? Thanks in advance! code: [Bindable] private var myList:ArrayCollection= new ArrayCollection(); private function getList(e:Event):void{ var getStudyLoungesService:HTTPService = new HTTPService(); getStuffService.url = "website.com/asdf.php"; getStuffService.addEventListener(ResultEvent.RESULT, onGetList); getStuffService.send(); } private function onGetList(e:ResultEvent):void{ myList= e.result.list.name; }

    Read the article

  • Instantiating a System.Threading.Thread object in Jscript

    - by user297029
    I'm trying to create a new System.Threading.Thread object using Jscript, but I can't get the constructor to work. If I just do the following, var thread = new Thread( threadFunc ); function threadFunc() { // do stuff } then I get error JS1184: More than one constructor matches this argument list. However, if I try to coerce threadFunc to System.Threading.ThreadStart via var thread = new Thread( ThreadStart(threadFunc) ) I get error JS1208: The specified conversion or coercion is not possible Anyone know how to do this? It seems like it should be trivial.

    Read the article

  • adobe flash buider (flex4): addChild() is not available in this class.

    - by ufk
    Hi. I want to be able to load an swf into a flex 4 application in order to use it's classes. var ldr:Loader=new Loader(); ldr.load(new URLRequest("file://path/to/fileswf")); ldr.contentLoaderInfo. addEventListener(Event.INIT, loaded); function loaded(evt:Event):void { addChild(ldr); } i receive the error: Error: addChild() is not available in this class. Instead, use addElement() or modify the skin, if you have one. at spark.components.supportClasses::SkinnableComponent/addChild()[E:\dev\gumbo_beta2\frameworks\projects\spark\src\spark\components\supportClasses\SkinnableComponent.as:966] at main/private:init/loaded()[C:\Documents and Settings\ufk\Adobe Flash Builder Beta 2\xpogames-toolkit-test\src\main.mxml:22] if i change addChild() to addElement() i receive the following compilation error: 1067: Implicit coercion of a value of type flash.display:Loader to an unrelated type mx.core:IVisualElement. main.mxml path/dir line 22 Flex Problem any ideas how to resolve the issue ?

    Read the article

  • Create WPF TextBox that accepts only numbers

    - by Elad
    I would like to create a TextBox that only accepts numeric values, in a specific range. What is the best way to implement such TextBox? I thought about deriving TextBox and to override the validation and coercion of the TextProperty. However, I am not sure how to do this, and I understand that deriving WPF control is generally not recommended. Edit: What I needed was a very basic textbox that filters out all key presses which are not digits. The easiest way to achieve it is to handle the TextBox.PreviewTextInput event: private void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { int result; if (!validateStringAsNumber(e.Text,out result,false)) { e.Handled = true; } } (validateStringAsNumber is my function that primarily use Int.TryParse) Some of the suggested solutions are probably better, but for the simple functionality I needed this solution is the easiest and quickest to implement while sufficient for my needs.

    Read the article

1 2 3  | Next Page >