Search Results

Search found 8223 results on 329 pages for 'odd behavior'.

Page 1/329 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Event Driven Behavior Tree: deterministic traversal order with parallel

    - by Heisenbug
    I've studied several articles and listen some talks about behavior trees (mostly the resources available on AIGameDev by Alex J. Champandard). I'm particularly interested on event driven behavior trees, but I have still some doubts on how to implement them correctly using a scheduler. Just a quick recap: Standard Behavior Tree Each execution tick the tree is traversed from the root in depth-first order The execution order is implicitly expressed by the tree structure. So in the case of behaviors parented to a parallel node, even if both children are executed during the same traversing, the first leaf is always evaluated first. Event Driven BT During the first traversal the nodes (tasks) are enqueued using a scheduler which is responsible for updating only running ones every update The first traversal implicitly produce a depth-first ordered queue in the scheduler Non leaf nodes stays suspended mostly of the time. When a leaf node terminate(either with success or fail status) the parent (observer) is waked up allowing the tree traversing to continue and new tasks will be enqueued in the scheduler Without parallel nodes in the tree there will be up to 1 task running in the scheduler Without parallel nodes, the tasks in the queue(excluding dynamic priority implementation) will be always ordered in a depth-first order (is this right?) Now, from what is my understanding of a possible implementation, there are 2 requirements I think must be respected(I'm not sure though): Now, some requirements I think needs to be guaranteed by a correct implementation are: The result of the traversing should be independent from which implementation strategy is used. The traversing result must be deterministic. I'm struggling trying to guarantee both in the case of parallel nodes. Here's an example: Parallel_1 -->Sequence_1 ---->leaf_A ---->leaf_B -->leaf_C Considering a FIFO policy of the scheduler, before leaf_A node terminates the tasks in the scheduler are: P1(suspended),S1(suspended),leaf_A(running),leaf_C(running) When leaf_A terminate leaf_B will be scheduled (at the end of the queue), so the queue will become: P1(suspended),S1(suspended),leaf_C(running),leaf_B(running) In this case leaf_B will be executed after leaf_C at every update, meanwhile with a non event-driven traversing from the root node, the leaf_B will always be evaluated before leaf_A. So I have a couple of question: do I have understand correctly how event driven BT work? How can I guarantee the depth first order is respected with such an implementation? is this a common issue or am I missing something?

    Read the article

  • Using Behavior Trees and Events together

    - by weichsem
    I am beginning to work with behavior trees and am unsure how events should be handled within the tree. Lets say we have a space game where the player is dogfighting with a handful of other ships, some friendly some not. The player destroys a ship and the rest of the hostile ships should then start to retreat. How was should the shipWasDestroyed event effect the other ship's behavior trees so that they start running the retreat behavior? One way I could think of doing this is have all the conditions I care about be high level nodes that effectively state change the ship. This would mean I'd have to check all of these state change conditions on every frame the behavior tree was run, even if they are very rare occurrences. I'd prefer not doing this for performance and complexity reasons. From looking at the Halo papers on behavior trees it seems that they handled this by dynamically placing nodes into the tree when the event occurred. It seems like calculating where the new node should go could be problematic depending on the current state of the running behavior. How is this normally handled?

    Read the article

  • Behavior Trees and Animations

    - by Tom
    I have started working on the AI for a game, but am confused how I should handle animations. I will be using a Behavior Tree for AI behavior and Cocos2D for my game engine. Should my "PlayAnimationWalk" just be another node in the tree? Something similar to this: [Approach Player] - Play Walk animation - Move Towards player - Stop Walk animation Or should the node just update an AnimationState in the blackboard and have some type of animation handler/component reference this for which animation should be playing? This has been driving me nuts :)

    Read the article

  • Behavior tree implementation details

    - by angryInsomniac
    I have been looking around for implementation details of behavior trees, the best descriptions I found were by Alex Champarand and some of Damian Isla's talk about AI in Halo 2 (the video of which is locked up in the GDC vault sadly). However, both descriptions fall short of helping one actually create a BT, one particular question has been bugging me for a while. When is the tree in a behavior tree evaluated? Furthermore: If the tree is in the middle of executing a sequence of actions (patrolling waypoints) and a higher priority impulse comes in (distraction sound) , how to switch to that side of the tree seamlessly without resorting to a state machine like system and if it is decided that the impulse was irrelevant (the distraction is too far away to affect this guard), how to go back to the last thing that the guard was doing ? I have quite a few questions like this and I don't wish to flood the board with separate queries so if you know of any resource where questions like these can be answered I would be very grateful.

    Read the article

  • SQL Server 2008 Designer Behavior Change: Saving Changes Not Permitted

    - by SAMIR BHOGAYTA
    Warning Message: Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created. This is by design and can be quickly fixed in Management Studio by unchecking a property. To fix this in Management Studio, go to Tools - Options then go to the Designer Page and uncheck "Prevent saving changes that require table re-creation"

    Read the article

  • DX11 - Weird shader behavior with and without branching

    - by Martin Perry
    I have found problem in my shader code, which I dont´t know how to solve. I want to rewrite this code without "ifs" tmp = evaluate and result is 0 or 1 (nothing else) if (tmp == 1) val = X1; if (tmp == 0) val = X2; I rewite it this way, but this piece of code doesn ´t word correctly tmp = evaluate and result is 0 or 1 (nothing else) val = tmp * X1 val = !tmp * X2 However if I change it to: tmp = evaluate and result is 0 or 1 (nothing else) val = tmp * X1 if (!tmp) val = !tmp * X2 It works fine... but it is useless because of "if", which need to be eliminated I honestly don´t understand it Posted Image . I tried compilation with NO and FULL optimalization, result is same

    Read the article

  • Optimize code performance when odd/even threads are doing different things in CUDA

    - by Orion Nebula
    Hi all! I have two large vectors, I am trying to do some sort of element multiplication, where an even-numbered element in the first vector is multiplied by the next odd-numbered element in the second vector .... and where the odd-numbered element in the first vector is multiplied by the preceding even-numbered element in the second vector Ex. vector 1 is V1(1) V1(2) V1(3) V1(4) vector 2 is V2(1) V2(2) V2(3) V2(4) V1(1) * V2(2) V1(3) * V2(4) V1(2) * V2(1) V1(4) * V2(3) I have written a Cuda code to do this: (Pds has the elements of the first vector in shared memory, Nds the second Vector) //instead of using %2 .. i check for the first bit to decide if number is odd/even -- faster if ((tx & 0x0001) == 0x0000) Nds[tx+1] = Pds[tx] * Nds[tx+1]; else Nds[tx-1] = Pds[tx] * Nds[tx-1]; __syncthreads(); Is there anyway to further accelerate this code or avoid divergence ? Thanks

    Read the article

  • Optimize code perfromance when odd/even threads are doing different things in CUDA

    - by Ashraf
    Hi all! I have two large vectors, I am trying to do some sort of element multiplication, where an even-numbered element in the first vector is multiplied by the next odd-numbered element in the second vector .... and where the odd-numbered element in the first vector is multiplied by the preceding even-numbered element in the second vector Ex. vector 1 is V1(1) V1(2) V1(3) V1(4) vector 2 is V2(1) V2(2) V2(3) V2(4) V1(1) * V2(2) V1(3) * V2(4) V1(2) * V2(1) V1(4) * V2(3) I have written a Cuda code to do this: (Pds has the elements of the first vector in shared memory, Nds the second Vector) //instead of using %2 .. i check for the first bit to decide if number is odd/even -- faster if ((tx & 0x0001) == 0x0000) Nds[tx+1] = Pds[tx] * Nds[tx+1]; else Nds[tx-1] = Pds[tx] * Nds[tx-1]; __syncthreads(); Is there anyway to further accelerate this code or avoid divergence .. Thanks

    Read the article

  • Firefox location bar search: odd behaviour with Comodo firewall

    - by JNat
    I recently installed Comodo firewall, and it changed the behaviour of my Firefox location bar. I used to type something there and it either redirected me to a google search page or it actually redirected me to the site I wanted at once: If I typed 'imdb cloud atlas' it would redirect me to IMDB's page on Cloud Atlas, and the same would happen if I typed 'wiki' or 'wikipedia', redirecting me to Wikipedia's page on it. Now, it redirects me here. I checked this page and everything is according to what they describe, yet it doesn't seem to act the way it should. And there are no Comodo add-ons or extensions installed on Firefox. Can anyone help me?

    Read the article

  • Is undefined behavior worth it?

    - by Space_C0wb0y
    Many bad things happened and continue to happen (or not, who knows, anything can happen) due to undefined behavior. I understand that this was introduced to leave some wiggle-room for compilers to optimize, and maybe also to make C++ easier to port to different platforms and architectures. However the problems caused by undefined behavior seem to be too large to be justified by these arguments. What are other arguments for undefined behavior? If there are none, why does undefined behavior still exist?

    Read the article

  • Undefined Behavior and Sequence Points Reloaded

    - by Nawaz
    Consider this topic a sequel of the following topic: Previous Installment Undefined Behavior and Sequence Points Let's revisit this funny and convoluted expression (the italicized phrases are taken from the above topic *smile* ): i += ++i; We say this invokes undefined-behavior. I presume that when say this, we implicitly assume that type of i is one of built-in types. So my question is: what if the type of i is a user-defined type? Say it's type is Index which is defined later in this post (see below). Would it still invoke undefined-behavior? If yes, why? Is it not equivalent to writing i.operator+=(i.operator ++()); or even syntactically simpler i.add(i.inc());? Or, do they too invoke undefined-behavior? If no, why not? After all, the object i gets modified twice between consecutive sequence points. Please recall the rule of thumb : an expression can modify an object's value only once between consecutive "sequence points. And if i += ++i is an expression, then it must invoke undefined-behavior. If so, then it's equivalents i.operator+=(i.operator ++()); and i.add(i.inc()); must also invoke undefined-behavior which seems to be untrue! (as far as I understand) Or, i += ++i is not an expression to begin with? If so, then what is it and what is the definition of expression? If it's an expression, and at the same time, it's behavior is also well-defined, then it implies that number of sequence points associated with an expression somehow depends on the type of operands involved in the expression. Am I correct (even partly)? By the way, how about this expression? a[++i] = i; //taken from the previous topic. but here type of `i` is Index. class Index { int state; public: Index(int s) : state(s) {} Index& operator++() { state++; return *this; } Index& operator+=(const Index & index) { state+= index.state; return *this; } operator int() { return state; } Index & add(const Index & index) { state += index.state; return *this; } Index & inc() { state++; return *this; } };

    Read the article

  • Django: Odd mark_safe behaviour?

    - by Mark
    I wrote this little function for writing out HTML tags: def html_tag(tag, content=None, close=True, attrs={}): lst = ['<',tag] for key, val in attrs.iteritems(): lst.append(' %s="%s"' % (key, escape_html(val))) if close: if content is None: lst.append(' />') else: lst.extend(['>', content, '</', tag, '>']) else: lst.append('>') return mark_safe(''.join(lst)) Which worked great, but then I read this article on efficient string concatenation (I know it doesn't really matter for this, but I wanted consistency) and decided to update my script: def html_tag(tag, body=None, close=True, attrs={}): s = StringIO() s.write('<%s'%tag) for key, val in attrs.iteritems(): s.write(' %s="%s"' % (key, escape_html(val))) if close: if body is None: s.write(' />') else: s.write('>%s</%s>' % (body, tag)) else: s.write('>') return mark_safe(s.getvalue()) But now my HTML get escaped when I try to render it from my template. Everything else is exactly the same. It works properly if I replace the last line with return mark_safe(unicode(s.getvalue())). I checked the return type of s.getvalue(). It should be a str, just like the first function, so why is this failing?? Also fails with SafeString(s.getvalue()) but succeeds with SafeUnicode(s.getvalue()). I'd also like to point out that I used return mark_safe(s.getvalue()) in a different function with no odd behavior. The "call stack" looks like this: class Input(Widget): def render(self): return html_tag('input', attrs={'type':self.itype, 'id':self.id, 'name':self.name, 'value':self.value, 'class':self.itype}) class Field: def __unicode__(self): return mark_safe(self.widget.render()) And then {{myfield}} is in the template. So it does get mark_safed'd twice, which I thought might have been the problem, but I tried removing that too..... I really have no idea what's causing this, but it's not too hard to work around, so I guess I won't fret about it.

    Read the article

  • Odd behaviour with PHP's in_array function.

    - by animuson
    I have a function that checks multiple form items and returns either boolean(true) if the check passed or the name of the check that was run if it didn't pass. I built the function to run multiple checks at once, so it will return an array of these results (one result for each check that was run). When I run the function, I get this array result: Array ( [0] => 1 [1] => password [2] => birthday ) // print_r array(3) { [0]=> bool(true) [1]=> string(8) "password" [2]=> string(8) "birthday" } // var_dump The 'username' check passed and the 'password' and 'birthday' checks both failed. Then I am using simple in_array statements to determine which ones failed, like so: $results = $ani->e->vld->simulate("register.php", $checks); die(var_dump($results)); // Added after to see what array was being returned if (in_array("username", $results)) // do something if (in_array("password", $results)) // do something if (in_array("birthday", $results)) // do something The problem I'm having is that the 'username' line is still executing, even those 'username' is not in the array. It executes all three statements as if they were all true for some reason. Why is this? I thought maybe that the bool(true) was automatically causing the function to return true for every result without checking the rest of the array, but I couldn't find any documentation that would suggest that very odd functionality.

    Read the article

  • PHP: Odd behaviour with date_sunset function

    - by Svish
    I'm having a look at the date_sunset function in PHP and have met an issue that I find a bit strange. I have this piece of code: $sunset = date_sunset(mktime(0, 0, 0, 5, 14, 2010), $format, // Format 55.596041, // Latitude 12.992495, // Longitude 90, // Zenith 2 // GMT Offset ); For the three different formats, that would give me: SUNFUNCS_RET_STRING 21:05 SUNFUNCS_RET_DOUBLE 21.095732016315 SUNFUNCS_RET_TIMESTAMP 1273863944 // H:i:s O -> 19:05:44 +0000 Why is the timestamp format ignoring the gmt offset? Is is supposed to be like that? If so what is the reason behind that?

    Read the article

  • Explicit behavior with checks vs. implicit behavior

    - by Silviu
    I'm not sure how to construct the question but I'm interested to know what do you guys think of the following situations and which one would you prefer. We're working at a client-server application with winforms. And we have a control that has some fields automatically calculated upon filling another field. So we're having a field currency which when filled by the user would determine an automatic filling of another field, maybe more fields. When the user fills the currency field, a Currency object would be retrieved from a cache based on the string introduced by the user. If entered currency is not found in the cache a null reference is returned by the cache object. Further down when asking the application layer to compute the other fields based on the currency, given a null currency a null specific field would be returned. This way the default, implicit behavior is to clear all fields. Which is the expected behavior. What i would call the explicit implementation would be to verify that the Currency object is null in which case the depending fields are cleared explicitly. I think that the latter version is more clear, less error prone and more testable. But it implies a form of redundancy. The former version is not as clear and it implies a certain behavior from the application layer which is not expressed in the tests. Maybe in the lower layer tests but when the need arises to modify the lower layers, so that given a null currency something else should be returned, i don't think a test that says just that without a motivation is going to be an impediment for introducing a bug in upper layers. What do you guys think?

    Read the article

  • How to spot undefined behavior

    - by BlueRaja - Danny Pflughoeft
    Is there any way to know if you program has undefined behavior in C++ (or even C), short of memorizing the entire spec? The reason I ask is that I've noticed a lot of cases of programs working in debug but not release being due to undefined behavior. It would be nice if there were a tool to at least help spot UB, so we know there's the potential for problems.

    Read the article

  • program that writes the even and odd numbers

    - by user292489
    enter code herei was writting a program that can read a set of numbers file called dog.txt; and also writes to two file separating odd and even. i was able to compile my program however, the output expected is not the same which was supposed to be even numbers in one file called EVEN, odd numbers in file odd. #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i; int even,odd; int num; if (argc != 4) { printf("Usage: executable in_file output_file\n"); exit(0); } FILE *dog = fopen(argv[1], "r"); FILE *feven= fopen(argv[2], "w"); FILE *fodd= fopen (argv[3], "w"); while (fscanf(dog, "%d", &num) != EOF) { if (0==i%2){ i++; printf("even= %d\n", num); } else if(i!=0){ i++; printf("odd= %d\n", num); } } fclose(feven); fclose(fodd); fclose(dog); return 0; } output: even= 1 odd= 2 even= 34 odd= 44 even= 66 odd= 78 even= 94 odd= 21 even= 23 odd= 54 even= 44 odd= 65 even= 78 odd= 68 even= 92

    Read the article

  • Can I use a specific model from within a behavior in CakePHP?

    - by Paul Willy
    I'm trying to write a behavior that will give my models access to a simple workflow engine I've devised. The workflow engine itself works as a CakePHP model, with workflow data stored in the database just as any other model data is stored. Basically what I want to do is have the behavior use the workflow model whenever an action is called on the base model. For example, if the edit() action is executed for Posts, then the Post (with the behavior attached) will trigger the workflow behavior with its own model name, action, and id as arguments (e.g. [Post, edit, 1]). Then the behavior will invoke the functionality of the Workflow model, which has a record for what to do when edit is run on Posts (e.g. send e-mail to users who are subscribed to that post) and will carry that out. My question is, what is the proper way to invoke model/controller methods from within the behavior? The model to be used from within the behavior will always be Workflow, but the behavior should be usable from basically any model (aside from Workflow itself). I know I could run SQL queries directly from the behavior, but of course this is not the Cake way :-) Or, am I going about this in the wrong way? I want to store a certain amount of logic in the database so that it is easily configurable by different users, and not have endless configuration checks within the model/controller logic itself so that workflow steps can be easily added/changed/removed in the future.

    Read the article

  • Javascript undefined behavior with string.replace

    - by epochwolf
    I've been messing around with string.replace and I noticed something very odd with Webkit and Firebug's javascript consoles. I can repeat this behavior in a blank browser window. (Look at the first and last lines) >>> "/literature?page=".replace(/page=/i, "page=2") "/literature?page=" >>> "/literature?page=".replace("page=", "page=2") "/literature?page=2" >>> "/literature?page=".replace(/page=/, "page=2") "/literature?page=2" >>> "/literature?page=".replace(/page=/i, "page=2") "/literature?page=2" Just so nobody thinks I mistyped something, here are screenshots. Firebug (3.0.14) Webkit (Latest nightly as of this post's creation.)

    Read the article

  • Learn Behavior-Driven Development

    - by Ben Griswold
    In this presentation, I provided a brief introduction into TDD and talked about the confusion and misconceptions around the discipline. I, of course, shared a bit about Dan North, the father of BDD and touched upon some crazy hypothesis dreamed up by Sapir and Whorf. I then gave a Behavior Driven Development overview (my impressions of the implementation and lifecycle) and then touched upon available tools, how to get started and I threw in a number of reference and reading materials which you will find below. As an added bonus, I demonstrated how easy it is to include/exclude hyphens and alter the spelling of “behavior” at will.   Introducing BDD, Dan North Oredev 2007 – Behaviour-Driven Development, Dan North Behavior-Driven Development, Scott Bellware Behavior Driven Development, Wikipedia BDD Wiki A New Look at Test-Driven Development, Dave Astels Behavior Driven Development – An Evolution in Testing, Bob Cotton The Truth about BDD, Uncle Bob Martin Language and Thought, Wikipedia Sapir-Whorf Hypothesis, Wikipedia What’s in a Story?, Dan North

    Read the article

  • C# - foreach showing strange behavior / for working with no problem

    - by Marks
    Hi there. Today I coded a function that uses two nested foreach loops. After seeing, that it did not work like expected, i debugged it. But I dont see an error, and dont think a simple error can cause the behavior i have noticed. The part looks like this: foreach(MyClass cItem in checkedListBoxItemList.Items) { foreach(MyClass cActiveItem in ActiveItemList) { if (cActiveItem.ID == cItem.ID) /*...check checkbox for item...*/; } } Lets say, checkedListBoxItemList.items holds 4 items of type MyClass, and ActiveItemList is a List< MyClass with 2 Items. The debugger jumps into the outer foreach, reaches inner foreach, executes the if 2 times (once per cActiveItem) and reaches the end of the outer foreach.Now, the debugger jumps back to the head of the outer foreach as it should. But instead of starting the second round of the outer foreach, the debugger suddenly jumps into the MyClass.ToString() method. I can step through this method 4 times (number of items in checkedListBoxItemList.Items) and then ... nothing. Visual Studio shows me my windows form, and the foreach is not continued. When changing the code to int ListCount = checkedListBoxItemList.Items.Count; for(int i=0; i<ListCount; i++) { MyClass cItem = checkedListBoxItemList.Items[i] as MyClass; foreach(MyClass cActiveItem in ActiveItemList) { if (cActiveItem.ID == cItem.ID) /*...check checkbox for item...*/; } } everything works fine and as supposed. I showed the problem to a collegue, but he also didnt understand, what happened. I dont understand why the debugger jumps into the MyClass.ToString() method. I used F10 to step through, so no need to leave the function. And even, if there is a reason, why isnt the foreach loop continued? Im using Visual Studio 2010, if this is of any matter. Please tell me what happened. Thanks.

    Read the article

  • Silverlight Center And Scale Behavior

    - by Jacek Ciereszko
    If you are interested in my last post about "How to center and scale Silverlight applications using ViewBox control", I just published behavior that you can use instead of making changes in code. How it works? 1. Download behavior (http://gallery.expression.microsoft.com/en-us/CenterAndScale ) 2. Add dll to your application <UserControl .....     xmlns:interaction="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"            xmlns:behavior="clr-namespace:CenterAncScaleBehavior;assembly=CenterAncScaleBehavior"  .... >     <interaction:Interaction.Behaviors>         <behavior:CenterAncScaleBehavior />     </interaction:Interaction.Behaviors>     <Grid > ... </Grid> </UserControl> 3. DONE! Your application is ready!   Watch movie to see how it works (66 seconds): See examples Application without "Center And Scale Behavior":  http://bit.ly/cVinEC Application with "Center And Scale Behavior":  http://bit.ly/ba8UsI   Source code and dlls http://gallery.expression.microsoft.com/en-us/CenterAndScale   Cheers! Jacek Ciereszko

    Read the article

  • Strange (Undefined?) Behavior of Free in C

    - by Chris Cirefice
    This is really strange... and I can't debug it (tried for about two hours, debugger starts going haywire after a while...). Anyway, I'm trying to do something really simple: Free an array of strings. The array is in the form: char **myStrings. The array elements are initialized as: myString[index] = malloc(strlen(word)); myString[index] = word; and I'm calling a function like this: free_memory(myStrings, size); where size is the length of the array (I know this is not the problem, I tested it extensively and everything except this function is working). free_memory looks like this: void free_memory(char **list, int size) { for (int i = 0; i < size; i ++) { free(list[i]); } free(list); } Now here comes the weird part. if (size> strlen(list[i])) then the program crashes. For example, imagine that I have a list of strings that looks something like this: myStrings[0] = "Some"; myStrings[1] = "random"; myStrings[2] = "strings"; And thus the length of this array is 3. If I pass this to my free_memory function, strlen(myStrings[0]) > 3 (4 3), and the program crashes. However, if I change myStrings[0] to be "So" instead, then strlen(myStrings[0]) < 3 (2 < 3) and the program does not crash. So it seems to me that free(list[i]) is actually going through the char[] that is at that location and trying to free each character, which I imagine is undefined behavior. The only reason I say this is because I can play around with the size of the first element of myStrings and make the program crash whenever I feel like it, so I'm assuming that this is the problem area. Note: I did try to debug this by stepping through the function that calls free_memory, noting any weird values and such, but the moment I step into the free_memory function, the debugger crashes, so I'm not really sure what is going on. Nothing is out of the ordinary until I enter the function, then the world explodes. Another note: I also posted the shortened version of the source for this program (not too long; Pastebin) here. I am compiling on MinGW with the c99 flag on. PS - I just thought of this. I am indeed passing numUniqueWords to the free function, and I know that this does not actually free the entire piece of memory that I allocated. I've called it both ways, that's not the issue. And I left it how I did because that is the way that I will be calling it after I get it to work in the first place, I need to revise some of my logic in that function. Source, as per request (on-site): #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include "words.h" int getNumUniqueWords(char text[], int size); int main(int argc, char* argv[]) { setvbuf(stdout, NULL, 4, _IONBF); // For Eclipse... stupid bug. --> does NOT affect the program, just the output to console! int nbr_words; char text[] = "Some - \"text, a stdin\". We'll have! also repeat? We'll also have a repeat!"; int length = sizeof(text); nbr_words = getNumUniqueWords(text, length); return 0; } void free_memory(char **list, int size) { for (int i = 0; i < size; i ++) { // You can see that printing the values is fine, as long as free is not called. // When free is called, the program will crash if (size > strlen(list[i])) //printf("Wanna free value %d w/len of %d: %s\n", i, strlen(list[i]), list[i]); free(list[i]); } free(list); } int getNumUniqueWords(char text[], int length) { int numTotalWords = 0; char *word; printf("Length: %d characters\n", length); char totalWords[length]; strcpy(totalWords, text); word = strtok(totalWords, " ,.-!?()\"0123456789"); while (word != NULL) { numTotalWords ++; printf("%s\n", word); word = strtok(NULL, " ,.-!?()\"0123456789"); } printf("Looks like we counted %d total words\n\n", numTotalWords); char *uniqueWords[numTotalWords]; char *tempWord; int wordAlreadyExists = 0; int numUniqueWords = 0; char totalWordsCopy[length]; strcpy(totalWordsCopy, text); for (int i = 0; i < numTotalWords; i++) { uniqueWords[i] = NULL; } // Tokenize until all the text is consumed. word = strtok(totalWordsCopy, " ,.-!?()\"0123456789"); while (word != NULL) { // Look through the word list for the current token. for (int j = 0; j < numTotalWords; j ++) { // Just for clarity, no real meaning. tempWord = uniqueWords[j]; // The word list is either empty or the current token is not in the list. if (tempWord == NULL) { break; } //printf("Comparing (%s) with (%s)\n", tempWord, word); // If the current token is the same as the current element in the word list, mark and break if (strcmp(tempWord, word) == 0) { printf("\nDuplicate: (%s)\n\n", word); wordAlreadyExists = 1; break; } } // Word does not exist, add it to the array. if (!wordAlreadyExists) { uniqueWords[numUniqueWords] = malloc(strlen(word)); uniqueWords[numUniqueWords] = word; numUniqueWords ++; printf("Unique: %s\n", word); } // Reset flags and continue. wordAlreadyExists = 0; word = strtok(NULL, " ,.-!?()\"0123456789"); } // Print out the array just for funsies - make sure it's working properly. for (int x = 0; x <numUniqueWords; x++) { printf("Unique list %d: %s\n", x, uniqueWords[x]); } printf("\nNumber of unique words: %d\n\n", numUniqueWords); // Right below is where things start to suck. free_memory(uniqueWords, numUniqueWords); return numUniqueWords; }

    Read the article

  • TDD and WCF behavior

    - by Frederic Hautecoeur
    Some weeks ago I wanted to develop a WCF behavior using TDD. I have lost some time trying to use mocks. After a while i decided to just use a host and a client. I don’t like this approach but so far I haven’t found a good and fast solution to use Unit Test for testing a WCF behavior. To Implement my solution I had to : Create a Dummy Service Definition; Create the Dummy Service Implementation; Create a host; Create a client in my test; Create and Add the behavior; Dummy Service Definition This is just a simple service, composed of an Interface and a simple implementation. The structure is aimed to be easily customizable for my future needs.   Using Clauses : 1: using System.Runtime.Serialization; 2: using System.ServiceModel; 3: using System.ServiceModel.Channels; The DataContract: 1: [DataContract()] 2: public class MyMessage 3: { 4: [DataMember()] 5: public string MessageString; 6: } The request MessageContract: 1: [MessageContract()] 2: public class RequestMessage 3: { 4: [MessageHeader(Name = "MyHeader", Namespace = "http://dummyservice/header", Relay = true)] 5: public string myHeader; 6:  7: [MessageBodyMember()] 8: public MyMessage myRequest; 9: } The response MessageContract: 1: [MessageContract()] 2: public class ResponseMessage 3: { 4: [MessageHeader(Name = "MyHeader", Namespace = "http://dummyservice/header", Relay = true)] 5: public string myHeader; 6:  7: [MessageBodyMember()] 8: public MyMessage myResponse; 9: } The ServiceContract: 1: [ServiceContract(Name="DummyService", Namespace="http://dummyservice",SessionMode=SessionMode.Allowed )] 2: interface IDummyService 3: { 4: [OperationContract(Action="Perform", IsOneWay=false, ProtectionLevel=System.Net.Security.ProtectionLevel.None )] 5: ResponseMessage DoThis(RequestMessage request); 6: } Dummy Service Implementation 1: public class DummyService:IDummyService 2: { 3: #region IDummyService Members 4: public ResponseMessage DoThis(RequestMessage request) 5: { 6: ResponseMessage response = new ResponseMessage(); 7: response.myHeader = "Response"; 8: response.myResponse = new MyMessage(); 9: response.myResponse.MessageString = 10: string.Format("Header:<{0}> and Request was <{1}>", 11: request.myHeader, request.myRequest.MessageString); 12: return response; 13: } 14: #endregion 15: } Host Creation The most simple host implementation using a Named Pipe binding. The GetBinding method will create a binding for the host and can be used to create the same binding for the client. 1: public static class TestHost 2: { 3: 4: internal static string hostUri = "net.pipe://localhost/dummy"; 5:  6: // Create Host method. 7: internal static ServiceHost CreateHost() 8: { 9: ServiceHost host = new ServiceHost(typeof(DummyService)); 10:  11: // Creating Endpoint 12: Uri namedPipeAddress = new Uri(hostUri); 13: host.AddServiceEndpoint(typeof(IDummyService), GetBinding(), namedPipeAddress); 14:  15: return host; 16: } 17:  18: // Binding Creation method. 19: internal static Binding GetBinding() 20: { 21: NamedPipeTransportBindingElement namedPipeTransport = new NamedPipeTransportBindingElement(); 22: TextMessageEncodingBindingElement textEncoding = new TextMessageEncodingBindingElement(); 23:  24: return new CustomBinding(textEncoding, namedPipeTransport); 25: } 26:  27: // Close Method. 28: internal static void Close(ServiceHost host) 29: { 30: if (null != host) 31: { 32: host.Close(); 33: host = null; 34: } 35: } 36: } Checking the service A simple test tool check the plumbing. 1: [TestMethod] 2: public void TestService() 3: { 4: using (ServiceHost host = TestHost.CreateHost()) 5: { 6: host.Open(); 7:  8: using (ChannelFactory<IDummyService> channel = 9: new ChannelFactory<IDummyService>(TestHost.GetBinding() 10: , new EndpointAddress(TestHost.hostUri))) 11: { 12: IDummyService svc = channel.CreateChannel(); 13: try 14: { 15: RequestMessage request = new RequestMessage(); 16: request.myHeader = Guid.NewGuid().ToString(); 17: request.myRequest = new MyMessage(); 18: request.myRequest.MessageString = "I want some beer."; 19:  20: ResponseMessage response = svc.DoThis(request); 21: } 22: catch (Exception ex) 23: { 24: Assert.Fail(ex.Message); 25: } 26: } 27: host.Close(); 28: } 29: } Running the service should show that the client and the host are running fine. So far so good. Adding the Behavior Add a reference to the Behavior project and add the using entry in the test class. We just need to add the behavior to the service host : 1: [TestMethod] 2: public void TestService() 3: { 4: using (ServiceHost host = TestHost.CreateHost()) 5: { 6: host.Description.Behaviors.Add(new MyBehavior()); 7: host.Open();¨ 8: …  If you set a breakpoint in your behavior and run the test in debug mode, you will hit the breakpoint. In this case I used a ServiceBehavior. To add an Endpoint behavior you have to add it to the endpoints. 1: host.Description.Endpoints[0].Behaviors.Add(new MyEndpointBehavior()) To add a contract or an operation behavior a custom attribute should work on the service contract definition. I haven’t tried that yet.   All the code provided in this blog and in the following files are for sample use. Improvements I don’t like to instantiate a client and a service to test my behaviors. But so far I have' not found an easy way to do it. Today I am passing a type of endpoint to the host creator and it creates the right binding type. This allows me to easily switch between bindings at will. I have used the same approach to test Mex Endpoints, another post should come later for this. Enjoy !

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >