Search Results

Search found 4451 results on 179 pages for 'red serpent'.

Page 22/179 | < Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >

  • Is creating a separate pool for each individual image created from a png appropriate?

    - by Panzercrisis
    I'm still possibly a little green about object-pooling, and I want to make sure something like this is a sound design pattern before really embarking upon it. Take the following code (which uses the Starling framework in ActionScript 3): [Embed(source = "/../assets/images/game/misc/red_door.png")] private const RED_DOOR:Class; private const RED_DOOR_TEXTURE:Texture = Texture.fromBitmap(new RED_DOOR()); private const m_vRedDoorPool:Vector.<Image> = new Vector.<Image>(50, true); . . . public function produceRedDoor():Image { // get a Red Door image } public function retireRedDoor(pImage:Image):void { // retire a Red Door Image } Except that there are four colors: red, green, blue, and yellow. So now we have a separate pool for each color, a separate produce function for each color, and a separate retire function for each color. Additionally there are several items in the game that follow this 4-color pattern, so for each of them, we have four pools, four produce functions, and four retire functions. There are more colors involved in the images themselves than just their predominant one, so trying to throw all the doors, for instance, in a single pool, and then changing their color properties around isn't going to work. Also the nonexistence of the static keyword is due to its slowness in AS3. Is this the right way to do things?

    Read the article

  • How to shift a vector based on the rotation of another vector?

    - by bpierre
    I’m learning 2D programming, so excuse my approximations, and please, don’t hesitate to correct me. I am just trying to fire a bullet from a player. I’m using HTML canvas (top left origin). Here is a representation of my problem: The black vector represent the position of the player (the grey square). The green vector represent its direction. The red disc represents the target. The red vector represents the direction of a bullet, which will move in the direction of the target (red and dotted line). The blue cross represents the point from where I really want to fire the bullet (and the blue and dotted line represents its movement). This is how I draw the player (this is the player object. Position, direction and dimensions are 2D vectors): ctx.save(); ctx.translate(this.position.x, this.position.y); ctx.rotate(this.direction.getAngle()); ctx.drawImage(this.image, Math.round(-this.dimensions.x/2), Math.round(-this.dimensions.y/2), this.dimensions.x, this.dimensions.y); ctx.restore(); This is how I instanciate a new bullet: var bulletPosition = playerPosition.clone(); // Copy of the player position var bulletDirection = Vector2D.substract(targetPosition, playerPosition).normalize(); // Difference between the player and the target, normalized new Bullet(bulletPosition, bulletDirection); This is how I move the bullet (this is the bullet object): var speed = 5; this.position.add(Vector2D.multiply(this.direction, speed)); And this is how I draw the bullet (this is the bullet object): ctx.save(); ctx.translate(this.position.x, this.position.y); ctx.rotate(this.direction.getAngle()); ctx.fillRect(0, 0, 3, 3); ctx.restore(); How can I change the direction and position vectors of the bullet to ensure it is on the blue dotted line? I think I should represent the shift with a vector, but I can’t see how to use it.

    Read the article

  • Sharing My Thoughts on Space Flight

    - by Grant Fritchey
    This went out in the DBA newsletter from Red Gate, but I enjoyed writing it so much, I thought I'd share it to a wider audience: I grew up watching the US space program. I watched men walk on the moon for the first time in 1969, when I was only six years old. From that moment on, I dreamed of going into space. I studied aeronautics and tried to get into the Air Force Academy, all in preparation for my long career as an astronaut. Clearly, that didn't quite work out for me. But it sure could for you. At Red Gate, we're running a new contest: DBA in Space. The prize is a sub-orbital flight. When I first got word of this contest, my immediate response was, "And you need me to go right away and do a test flight? Excellent!" No, no test flight needed, plus I was pretty low on the list of volunteers. "That's OK, I'll just enter." Then I was told that, as a Red Gate employee, I couldn't win. My next response was, "I quit".eventually, I was talked down off the ledge, and agreed to help make this special for some other DBA. Many (most?) of us are science fiction fans, either the soft science of Star Trek and Star Wars, or the hard science of Niven and Pournelle, or Allen Steele. We watched the Shuttles go up and land. We've been dreaming of our own trips into orbit and our vacation-home on the Moon for a long, long time. All that might not arrive on schedule, but you've got a shot at breaking clear of the atmosphere. The first stage is a video quiz, starring Brad McGehee, and it's live at www.DBAinSpace.com now. Go for it. Good luck and God speed!

    Read the article

  • Is creating a separate pool for each individual png image in the same class appropriate?

    - by Panzercrisis
    I'm still possibly a little green about object-pooling, and I want to make sure something like this is a sound design pattern before really embarking upon it. Take the following code (which uses the Starling framework in ActionScript 3): [Embed(source = "/../assets/images/game/misc/red_door.png")] private const RED_DOOR:Class; private const RED_DOOR_TEXTURE:Texture = Texture.fromBitmap(new RED_DOOR()); private const m_vRedDoorPool:Vector.<Image> = new Vector.<Image>(50, true); . . . public function produceRedDoor():Image { // get a Red Door image } public function retireRedDoor(pImage:Image):void { // retire a Red Door Image } Except that there are four colors: red, green, blue, and yellow. So now we have a separate pool for each color, a separate produce function for each color, and a separate retire function for each color. Additionally there are several items in the game that follow this 4-color pattern, so for each of them, we have four pools, four produce functions, and four retire functions. There are more colors involved in the images themselves than just their predominant one, so trying to throw all the doors, for instance, in a single pool, and then changing their color properties around isn't going to work. Also the nonexistence of the static keyword is due to its slowness in AS3. Is this the right way to do things?

    Read the article

  • Calculate travel time on road map with semaphores

    - by Ivansek
    I have a road map with intersections. At intersections there are semaphores. For each semaphore I generate a red light time and green light time which are represented with syntax [R:T1, G:T2], for example: 119 185 250 A ------- B: [R:6, G:4] ------ C: [R:5, G:5] ------ D I want to calculate a car travel time from A - D. Now I do this with this pseudo code: function get_travel_time(semaphores_configuration) { time = 0; for( i=1; i<path.length;i++) { prev_node = path[i-1]; next_node = path[i]); cost = cost_between(prev_node, next_node) time += (cost/movement_speed) // movement_speed = 50px per second light_times = get_light_times(path[i], semaphore_configurations) lights_cycle = get_lights_cycle(light_times) // Eg: [R,R,R,G,G,G,G], where [R:3, G:4] lights_sum = light_times.green_time+light_times.red_light; // Lights cycle time light = lights_cycle[cost%lights_sum]; if( light == "R" ) { time += light_times.red_light; } } return time; } So for distance 119 between A and B travel time is, 119/50 = 2.38s ( exactly mesaured time is between 2.5s and 2.6s), then we add time if we came at a red light when at B. If we came at a red light is calculated with lines: lights_cycle = get_lights_cycle(light_times) // Eg: [R,R,R,G,G,G,G], where [R:3, G:4] lights_sum = light_times.green_time+light_times.red_light light = lights_cycle[cost%lights_sum]; if( light == "R" ) { time += light_times.red_light; } This pseudo code doesn't calculate exactly the same times as they are mesaured, but the calculations are very close to them. Any idea how I would calculate this?

    Read the article

  • SQL Source Control Contest

    - by Ajarn Mark Caldwell
    If you’re a regular reader of this blog, you know that I have written several posts about how important I think it is to protect your source code, to version it, and in particular, all the aspects I like about Red Gate’s SQL Source Control product.  But for a moment, let’s take a break from my writing and I want to hear your stories.  What nightmare situation are you in, or can you imagine, where source control for your database would save the world.  Or maybe your life is not so dramatic, but you do see a challenge that, if you just had a good tool like SQL Source Control, it would go much smoother.  What’s your pain?  You have read my writings, now tell me your story, and be in the running for a free copy of SQL Source Control from Red Gate. Yes, that’s right.  Although I am just a fan of Red Gate, they have authorized me to give out a handful of licenses to blog readers who are willing to share their story by posting a comment to this blog entry.  Simply add your comment below (be sure to include a valid email address in the box that asks for that) to be entered.  The contest starts immediately and over the next few days, the best stories will win.

    Read the article

  • Problem with alleg42.dll / program crashes / Allegro & Codeblocks

    - by user24152
    I'm having a serious problem with allegro. The program should display random pixels on the screen and when I build and run it I get the following error message: Below is the full code of my program: #include <stdio.h> #include <stdlib.h> #include <time.h> #include "allegro.h" #define Text_Color_Red makecol(255,0,0) int main() { int ret; int color_depth = 32; int x; int y; int red; int green; int blue; int color; //init allegro allegro_init(); //install keyboard install_keyboard(); //set color depth to 32 bits set_color_depth(color_depth); //init random seed srand(time(NULL)); //init video mode to 640 x 480 ret = set_gfx_mode(GFX_AUTODETECT_WINDOWED,640,480,0,0); if(ret !=0) { allegro_message(allegro_error); return 1; } //Display string textprintf(screen,font,0,0,10,0,Text_Color_Red,"Screen Resolution is: %dx%d -- Press ESC to quit !",SCREEN_W,SCREEN_H); //display pixels until ESC key is pressed //wait for keypress while(!key[KEY_ESC]) { //set a random location x = 10 + rand() % (SCREEN_W-20); y = 10 + rand() % (SCREEN_H-20); //set a random color red = rand() % 255; green = rand() % 255; blue = rand() % 255; color = makecol(red,green,blue); //draw the pixel putpixel(screen, x, y, color); } //quit allegro allegro_exit(); } END_OF_MAIN() Error message: AllegroPixels1.exe has encountered a problem and needs to close. We are sorry for the inconvenience. Error signature: AppName: allegropixels1.exe AppVer: 0.0.0.0 ModName: alleg42.dll ModVer: 4.2.3.0 Offset: 0006c05c I am using Windows XP inside a virtual machine under Parallels 7.0

    Read the article

  • RasterizerState set to null after calling DrawText in Nuclex

    - by ProgrammerAtWork
    I have the following code in XNA: // class members Text t1; Text t2; Text t3; // init // Debugfont is size 24 vectorfont t1 = MM.DebugFont24.Fill("hello"); t1 = MM.DebugFont24.Extrude("hello"); t2 = MM.DebugFont24.Fill("hello"); t2 = MM.DebugFont24.Extrude("hello"); t3 = MM.DebugFont24.Fill("hello"); t3 = MM.DebugFont24.Extrude("hello"); // Draw TextBatch test = new TextBatch(MM.GD); test.DrawText(t1, Color.Red); test.DrawText(t2, Color.Red); test.DrawText(t3, Color.Red); test.End(); //After the second call to the TextBatch, RasterizerState of the GraphicsDevice is set to null //But I don't get any runtime errors or any indication of that something is wrong. Is this supposed to happen? Or am I doing something wrong? I've discovered that this happened because culling was set to None when I was rendering textures

    Read the article

  • How to pass one float as four unsigned chars to shader by glVertexPointAttrib?

    - by Kog
    For each vertex I use two floats as position and four unsigned bytes as color. I want to store all of them in one table, so I tried casting those four unsigned bytes to one float, but I am unable to do that correctly... All in all, my tests came to one point: GLfloat vertices[] = { 1.0f, 0.5f, 0, 1.0f, 0, 0 }; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), vertices); // VER1 - draws red triangle // unsigned char colors[] = { 0xff, 0, 0, 0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0, // 0xff }; // glEnableVertexAttribArray(1); // glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, 4 * sizeof(GLubyte), // colors); // VER2 - draws greenish triangle (not "pure" green) // float f = 255 << 24 | 255; //Hex:0xff0000ff // float colors2[] = { f, f, f }; // glEnableVertexAttribArray(1); // glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, 4 * sizeof(GLubyte), // colors2); // VER3 - draws red triangle int i = 255 << 24 | 255; //Hex:0xff0000ff int colors3[] = { i, i, i }; glEnableVertexAttribArray(1); glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, 4 * sizeof(GLubyte), colors3); glDrawArrays(GL_TRIANGLES, 0, 3); Above code is used to draw one simple red triangle. My question is - why do versions 1 and 3 work correctly, while version 2 draws some greenish triangle? Hex values are one I read by marking variable during debug. They are equal for version 2 and 3 - so what causes the difference?

    Read the article

  • What’s ‘default’ for?

    - by Strenium
    Sometimes there's a need to communicate explicitly that value variable is yet to be "initialized" or in other words - we’ve never changed it from its' default value. Perhaps "initialized" is not the right word since a value type will always have some sort of value (even a nullable one) but it's just that - how do we tell? Of course an 'int' would be 0, an 'enum' would the first defined value of a given enum and so on – we sure can make this kind of check "by hand" but eventually it would get a bit messy. There's a more elegant way with a use of little-known functionality of: 'default'Let’s just say we have a simple Enum: Simple Enum namespace xxx.Common.Domain{    public enum SimpleEnum    {        White = 1,         Black = 2,         Red = 3    }}   In case below we set the value of the enum to ‘White’ which happens to be a first and therefore default value for the enum. So the snippet below will set value of the ‘isDefault’ Boolean to ‘true’. 'True' Case SimpleEnum simpleEnum = SimpleEnum.White;bool isDefault; /* btw this one is 'false' by default */ isDefault = simpleEnum == default(SimpleEnum) ? true : false; /* default value 'white' */   Here we set the value to ‘Red’ and ‘default’ will tell us whether or not this the default value for this enum type. In this case: ‘false’. 'False' Case simpleEnum = SimpleEnum.Red; /* change from default */isDefault = simpleEnum == default(SimpleEnum) ? true : false; /* value is not default any longer */ Same 'default' functionality can also be applied to DateTimes, value types and other custom types as well. Sweet ‘n Short. Happy Coding!

    Read the article

  • Spritegroups and colorkeys

    - by Fristi
    I have a problem using spritegroups in pygame. In my situation I have 2 spritegroups, one for humans, one for "infected". A human is represented by a blue circle: image = pygame.Surface((32,32)) image.fill((255,255,255)) pygame.draw.circle(image,(0,0,255),(16,16),16) image = image.convert() image.set_colorkey((255,255,255)) An infected by a red one (same code, different color). I update my spritegroups as follows: self.humans.clear(self.screen, self.bg) self.humans.update(time_passed) self.humans.draw(self.screen) self.infected.clear(self.screen, self.bg) self.infected.update(time_passed) self.infected.draw(self.screen) Self.bg is defined: self.bg = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT)) self.bg.fill((255,255,255)) self.bg.convert() This all works, except that when a red circle overlaps with a blue one, you can see the white corners of the bounding box around the actual circle. Within a spritegroup it works, using the set_colorkey function. This does not happen with overlapping blue circles or overlapping red circles. I tried adding a colorkey to self.bg but that did not work. Same for adding a colorkey to self.screen.

    Read the article

  • How to group items by date range in XSLT?

    - by glenatron
    I have a bunch of data that looks a little like this: <item> <colour>Red</colour> <date_created>2009-10-10 12:01:55</date_created> <date_sold>2009-10-20 22:32:12</date_sold> </item> <item> <colour>Blue</colour> <date_created>2009-11-01 13:21:00</date_created> <date_sold>2009-11-21 12:32:12</date_sold> </item> <item> <colour>Blue</colour> <date_created>2009-10-29 21:23:02</date_created> <date_sold>2009-10-20 02:02:22</date_sold> </item> <item> <colour>Red</colour> <date_created>2009-11-02 09:11:51</date_created> <date_sold>2009-11-20 09:15:53</date_sold> </item> <item> <colour>Red</colour> <date_created>2009-10-18 11:00:55</date_created> <date_sold>2009-10-20 11:12:22</date_sold> </item> Now what I would like to be able to do is to run that through an XSLT stylesheet such that I get ouput looking like this: Colour | In stock 1 week | In stock 2 weeks | In stock 3 weeks Red | 1 | 3 | 2 Blue | 0 | 2 | 1 Currently I have a stylesheet that uses basic muenchian grouping to show that 30% of stock was Red and 70% blue, but I can't see a way to find the number of nodes withing a given date range. Is there a way to use keys to select a range? Do I need to create some kind of intermediate data node? Is there a different route that shows I'm barking up the wrong tree with both those suggestions? Is this even possible with XSLT or do I need to find a way to change the data source?

    Read the article

  • jQuery UI problem: why do the elements go flying around the screen?

    - by George Edison
    Yes, I know the title sounds a little suspicious. I will try to explain this the best I can... The code below is supposed to have the blue div slide down beside the red div. The first time you hit the Show the div button, it works. Also, the Hide the div works. Then when I click to show the div again, it appears to the right of where it is supposed to be! Why is this?!? Note: You can find a live example of the code here <html> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Demo</title> <style type='text/css'> #red { background-color: red; width: 200px; height: 150px; position: absolute; } #blue { background-color: blue; width: 150px; height: 200px; position: absolute; display: none; } #tester_1 { top: 300px; left: 300px; position: absolute; } #tester_2 { top: 350px; left: 300px; position: absolute; } </style> </head> <script type="text/javascript" src="jquery.js"></script> <script type='text/javascript'> function Show() { $('#blue').position({ of: $('#red'), my: 'left top', at: 'right top'}).slideDown(); } function Hide() { $('#blue').hide(); } </script> <body> <div id='red'></div> <div id='blue'></div> <button id='tester_1' onclick='Show()'>Show the <kbd>div</kbd></button> <button id='tester_2' onclick='Hide()'>Hide the <kbd>div</kbd></button> </body> </html>

    Read the article

  • Efficient method of finding database rows that have *one or more* qualities from a list of seven qualities

    - by hithere
    Hello! For this question, I'm looking to see if anyone has a better idea of how to implement what I'm currently planning on implementing (below): I'm keeping track of a set of images, using a database. Each image is represented by one row. I want to be able to search for images, using a number of different search parameters. One of these parameters involves a search-by-color option. (The rest of the search stuff is currently working fine.) Images in this database can contain up to seven colors: -Red -Orange -Yellow -Green -Blue -Indigo -Violet Here are some example user queries: "I want an image that contains red." "I want an image that contains red and blue." "I want an image that contains yellow and violet." "I want an image that contains red, orange, yellow, green, blue, indigo and violet." And so on. Users make this selection through the use of checkboxes in an html form. They can check zero checkboxes, all seven, and anything in between. I'm curious to hear what people think would be the most efficient way to perform this database search. I have two possible options right now, but I feel like there must be something better that I'm not thinking of. (Option 1) -For each row, simply have seven additional fields in the database, one for each color. Each field holds a 1 or 0 (true/false) value, and I SELECT based on whatever the user has checked off. (I didn't like this solution so much, because it seemed kind of wasteful to add seven additional fields...especially since most pictures in this table will only have 3-4 colors max, though some could have up to 7. So that means I'm storing a lot of zeros.) Also, if I added more searchable colors later on (which I don't think I will, but it's always possible), I'd have to add more fields. (Option 2) -For each image row, I could have a "colors" text field that stores space-separated color names (or numbers for the sake of compactness). Then I could do a fulltext match against search through the fields, selecting rows that contain "red yellow green" (or "1 3 4"). But I kind of didn't want to do fulltext searching because I already allow a keyword search, and I didn't really want to do two fulltext searches per image search. Plus, if the database gets big, fulltext stuff might slow down. Any better options that I didn't think of? Thanks! Side Note: I'm using PHP to work with a MySQL database.

    Read the article

  • KineticJS issue with repeatable mouse event

    - by nuclearpeace
    I have noob issue here (i obviously missing something). I simplified it from my bigger application: When i click blue rectangle, i add another layer to the stage that includes red rectangle (clickable), when i clik this red rectangle it removes second layer with red rect. Problem: When i click blue rect second time, nothing happens :( i.e. app works only once, and i need to add/remove second layer(with red rect) repeatedly. What's wrong? :) You can see it here, Fiddle http://jsfiddle.net/mAX8r/ Code: <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } canvas { border: 1px solid #9C9898; } </style> <script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.0.3.js"> </script> <script> window.onload = function() { var stage = new Kinetic.Stage({ container: 'container', width: 578, height: 200 }); var layerBlue = new Kinetic.Layer(); var layerRed = new Kinetic.Layer(); var rectBlue = new Kinetic.Rect({ x: 100, y: 75, width: 100, height: 50, fill: 'blue', stroke: 'black', strokeWidth: 4 }); var rectRed = new Kinetic.Rect({ x: 300, y: 75, width: 100, height: 50, fill: 'red', stroke: 'black', strokeWidth: 4 }); // mouse events rectBlue.on('click', function() { stage.add(layerRed); stage.draw(); }); rectRed.on('click', function() { layerRed.remove(); stage.draw(); }); // add the shape to the layer layerBlue.add(rectBlue); layerRed.add(rectRed); // add the layer to the stage stage.add(layerBlue); }; </script> </head> <body> <div id="container"></div> </body> </html>

    Read the article

  • Create a Search Filter List in Google Chrome

    - by Asian Angel
    Are you tired of unwanted and/or non-relevant results cluttering up the search results at Bing, Yahoo, and Google? With the Search Filter extension for Chrome you can easily remove the unwanted “chaff” from your search results. Note: The extension only works on Bing, Yahoo, and Google at this time. Before For our example we conducted a search for “anime wallpapers” at Yahoo Singapore, Bing Singapore, and Google. In each set of results we decided to focus on results that would display either a yellow or red warning color from WOT. You can see our targeted result for Yahoo Singapore… The one for Bing Singapore… And the targeted result from Google. Search Filter in Action As soon as you install the extension you should take a quick look at the “Options”. At first the “Filters List Area” will be empty but will not remain so for long as you create your own filter list. The second part may or may not be of interest to you…the ability to opt into the filter service. If you opt in your filter list will be connected to your “Google Account” and will be available on any of your Chrome installs with the extension installed (and set to “Opt In”). Keep in mind that if you choose this option the filter list that you create will be aggregated anonymously and have a GUID number attached to it. After installing the extension we refreshed each of our three search pages…notice the small red circle button beside each search result link. Clicking on the red circle button will cause the entire browser window area to “shade out” temporarily while you decide between adding that website to the filter list or cancelling the action. If you add a website to the filter list that result will immediately disappear from the search results list without refreshing the webpage. Looks like we have another website at the bottom that we could add to the filter list… Click, click, click! After adding one website from each of the three search services you can see that our filter list has gotten off to a nice start. If for some reason you accidentally add a website to the list or change your mind about a website simply click on the red circle button to remove that particular listing. Conclusion If you are looking for an easy way to create a search filter list then this is definitely an extension that is worth taking the time to look at. Links Download the Search Filter extension (Google Chrome Extensions) Visit the Search Filter Hub Website to View Lists of Filtered Sites Similar Articles Productive Geek Tips How to Make Google Chrome Your Default BrowserGeek’s Spam Filter – Updated to Version 0.2Access Wolfram Alpha Search in Google ChromeGain Access to a Search Box in Google ChromeGeek’s Spam Filter – Updated to Version 0.3 TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips Revo Uninstaller Pro Registry Mechanic 9 for Windows PC Tools Internet Security Suite 2010 PCmover Professional Scan News With NY Times Article Skimmer SpeedyFox Claims to Speed up your Firefox Beware Hover Kitties Test Drive Mobile Phones Online With TryPhone Ben & Jerry’s Free Cone Day, 3/23/10 New Stinger from McAfee Helps Remove ‘FakeAlert’ Threats

    Read the article

  • Communication between state machines with hidden transitions

    - by slartibartfast
    The question emerged for me in embedded programming but I think it can be applied to quite a number of general networking situations e.g. when a communication partner fails. Assume we have an application logic (a program) running on a computer and a gadget connected to that computer via e.g. a serial interface like RS232. The gadget has a red/green/blue LED and a button which disables the LED. The LEDs color can be driven by software commands over the serial interface and the state (red/green/blue/off) is read back and causes a reaction in the application logic. Asynchronous behaviour of the application logic with regard to the LED color down to a certain delay (depending on the execution cycle of the application) is tolerated. What we essentially have is a resource (the LED) which can not be reserved and handled atomically by software because the (organic) user can at any time press the button to interfere/break the software attempt to switch the LED color. Stripping this example from its physical outfit I dare to say that we have two communicating state machines A (application logic) and G (gadget) where G executes state changes unbeknownst to A (and also the other way round, but this is not significant in our example) and only A can be modified at a reasonable price. A needs to see the reaction and state of G in one piece of information which may be (slightly) outdated but not inconsistent with respect to the short time window when this information was generated on the side of G. What I am looking for is a concise method to handle such a situation in embedded software (i.e. no layer/framework like CORBA etc. available). A programming technique which is able to map the complete behaviour of both participants on classical interfaces of a classical programming language (C in this case). To complicate matters (or rather, to generalize), a simple high frequency communication cycle of A to G and back (IOW: A is rapidly polling G) is out of focus because of technical restrictions (delay of serial com, A not always active, etc.). What I currently see as a general solution is: the application logic A as one thread of execution an adapter object (proxy) PG (presenting G inside the computer), together with the serial driver as another thread a communication object between the two (A and PG) which is transactionally safe to exchange The two execution contexts (threads) on the computer may be multi-core or just interrupt driven or tasks in an RTOS. The com object contains the following data: suspected state (written by A): effectively a member of the power set of states in G (in our case: red, green, blue, off, red_or_green, red_or_blue, red_or_off...etc.) command data (written by A): test_if_off, switch_to_red, switch_to_green, switch_to_blue operation status (written by PG): operation_pending, success, wrong_state, link_broken new state (written by PG): red, green, blue, off The idea of the com object is that A writes whichever (set of) state it thinks G is in, together with a command. (Example: suspected state="red_or_green", command: "switch_to_blue") Notice that the commands issued by A will not work if the user has switched off the LED and A needs to know this. PG will pick up such a com object and try to send the command to G, receive its answer (or a timeout) and set the operation status and new state accordingly. A will take back the oject once it is no longer at operation_pending and can react to the outcome. The com object could be separated of course (into two objects, one for each direction) but I think it is convenient in nearly all instances to have the command close to the result. I would like to have major flaws pointed out or hear an entirely different view on such a situation.

    Read the article

  • News From EAP Testing

    - by Fatherjack
    There is a phrase that goes something like “Watch the pennies and the pounds/dollars will take care of themselves”, meaning that if you pay attention to the small things then the larger things are going to fare well too. I am lucky enough to be a Friend of Red Gate and once in a while I get told about new features in their tools and have a test copy of the software to trial. I got one of those emails a week or so ago and I have been exploring the SQL Prompt 6 EAP since then. One really useful feature of long standing in SQL Prompt is the idea of a code snippet that is automatically pasted into the SSMS editor when you type a few key letters. For example I can type “ssf” and then press the tab key and the text is expanded to SELECT * FROM. There are lots of these combinations and it is possible to create your own really easily. To create your own you use the Snippet Manager interface to define the shortcut letters and the code that you want to have put in their place. Let’s look at an example. Say I am writing a blog about something and want to have the demo code create a temporary table. It might looks like this; The first time you run the code everything is fine, a lovely set of dates fill the results grid but run it a second time and this happens.   Yep, we didn’t destroy the temporary table so the CREATE statement fails when it finds the table already exists. No matter, I have a snippet created that takes care of this.   Nothing too technical here but you will see that in the Code section there is $CURSOR$, this isn’t a TSQL keyword but a marker for SQL Prompt to place the cursor in that position when the Code is pasted into the SSMS Editor. I just place my cursor above the CREATE statement and type “ifobj” – the shortcut for my code to DROP the temporary table – which has been defined in the Snippet Manager as below. This means I am right-away ready to type the name of the offending table. Pretty neat and it’s been very useful in saving me lots of time over many years.   The news for SQL Prompt 6 is that Red Gate have added a new Snippet Command of $PASTE$. Let’s alter our snippet to the following and try it out   Once again, we will type type “ifobj” in the SSMS Editor but first of all, highlight the name of the table #TestTable and copy it to your clipboard. Now type “ifobj” and press Tab… Wherever the string $PASTE$ is placed in the snippet, the contents of your clipboard are merged into the pasted TSQL. This means I don’t need to type the table name into the code snippet, it’s already there and I am seeing a fully functioning piece of TSQL ready to run. This means it is it even easier to write TSQL quickly and consistently. Attention to detail like this from Red Gate means that their developer tools stay on track to keep winning awards year after year and help take the hard work out of writing neat, accurate TSQL. If you want to try out SQL Prompt all the details are at http://www.red-gate.com/products/sql-development/sql-prompt/.

    Read the article

  • The World of SQL Database Deployment

    - by GGBlogger
    In my early development days, I used Microsoft Access for building databases. It made things easy since I only needed to package the database with the installation package so my clients would have access to it. When we began the development of a new package in Visual Studio .NET I decided to use SQL Server Express. It was free and provided good tools - also free. I thought it was a tremendous idea until it came time to distribute our new software! What a surprise. The nightmare Ah, the choices! Detach the database and have the client reattach it to a newly installed – oh wait. FIRST my new client needs to download and install SQL Server Express with SQL Server Management Studio. That’s not a great thing, but it is one more nightmare step for users who may have other versions of SQL installed. Then the question became – do we detach and reattach or do we do a backup. It was too late (bad planning) to revert to Microsoft Access but we badly needed a simple way to package and distribute both the database AND sample contents. Red Gate to the rescue It took me a while to find an answer but I did find it in a package called SQL Packager sold by a relatively unpublicized company in England called Red Gate. They call their products “ingeniously simple” and I must agree with that description. With SQL Packager you point to the database (more in a minute) you want to distribute. A few mouse clicks and dialogs and you have an executable file that you can ship virtually anywhere and virtually any way which, when run, installs the database on your destination SQL Server instance! It really is that simple. Easier to show than tell Let’s explore a hypothetical case. Let’s say you have a local SQL database of customers and you have decided you want to share it with your subsidiaries or partners. Here is the underlying screen you will see on starting SQL Packager. There are a bunch of possibilities here but I’m going to keep this relatively simple. At this point I simply want to illustrate the simplicity of generating an executable to deliver your database. You will notice that you can set up a new package, edit an existing package or change a bunch of options. Start SQL packager And the following is the default dialog you get on startup. In the next dialog, I’ve selected the Server and Database. I’ve also selected Windows Authentication. Pressing Next causes SQL Packager to run a number of checks and produce a report. Now you’re given a comprehensive list of what is going to be packaged and you’re allowed to change it if you desire. I’ve never made any changes here so I can’t really make any suggestions. The just illustrates the comprehensive nature of so many Red Gate products including this one. Clicking Next gives you still further options. SQL Packager then works its magic and shows you a dialog with the results. Packager then gives you a dialog of the scripts it has generated. The capture above only shows 1 of 4 tabs. Finally pressing Next gives you the option to generate a .NET executable of a C# project. I’ve only generated an executable so I’m not in a position to tell you what the C# project looks like. That may be the subject of further discussions. You can rename the package and tell SQL Packager where to save it. I’ve skipped a lot but this will serve to illustrate the comprehensive (and ingenious) things Red Gate does. All in all, it’s a superb way to distribute populated SQL databases. Oh – we’ll save running the resulting executable for later also but believe me it’s insanely simple.

    Read the article

  • Quel est le langage des "vrais" programmeurs ? Qu'utilise l'élite des développeurs ?

    Quel est le langage des "vrais" programmeurs ? Qu'utilise l'élite des développeurs ? Depuis des lustres, les programmeurs du monde entier s'affrontent dans une guerre très sérieuse pour déterminer quel est le meilleur langage de programmation existant, et surtout, quelle élite constitue le groupe des "vrais programmeurs". L'élite utilisant forcément la crème des langages, chacun défend sa paroisse. Pour des résultats pas toujours très objectifs... Et surtout, jamais en accord avec ceux de son voisin qui n'est forcément qu'un "noob", puisqu'il n'utilise pas le meilleur langage... C'est le serpent qui se mord la queue. Source : ...

    Read the article

  • Les 5 phases de l'évolution du développeur tête a claques, les avez-vous traversées ?

    Les 5 phases de l'évolution du développeur tête a claques, les avez-vous traversées ? Le développeur est un être comme un autre et, comme beaucoup, il traverse plusieurs étapes au cours de sa vie pour évoluer. Comment découper une carrière IT suivant ces grandes phases ? Nous en avons trouvées cinq, les voici : Le débutant enthousiaste Débordant de passion et d'excitation, particulièrement pour son langage fétiche (du genre VB ou PHP), le débutant code très vite, et pense maitriser totalement le syntaxe d'actionscript. Généralement, il ne produit que des gros fichiers remplis de variables. Il est très productif...si ce que vous recherchez est un jeu avec un serpent devant avaler des pommes sans toucher les ...

    Read the article

  • XNA WP7 Texture memory and ContentManager

    - by jlongstreet
    I'm trying to get my WP7 XNA game's memory under control and under the 90MB limit for submission. One target I identified was UI textures, especially fullscreen ones, that would never get unloaded. So I moved UI texture loads to their own ContentManager so I can unload them. However, this doesn't seem to affect the value of Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage"), so it doesn't look like the memory is actually being released. Example: splash screens. In Game.LoadContent(): Application.Instance.SetContentManager("UI"); // set the current content manager for (int i = 0; i < mSplashTextures.Length; ++i) { // load the splash textures mSplashTextures[i] = Application.Instance.Content.Load<Texture2D>(msSplashTextureNames[i]); } // set the content manager back to the global one Application.Instance.SetContentManager("Global"); When the initial load is done and the title screen starts, I do: Application.Instance.GetContentManager("UI").Unload(); The three textures take about 6.5 MB of memory. Before unloading the UI ContentManager, I see that ApplicationCurrentMemoryUsage is at 34.29 MB. After unloading the ContentManager (and doing a full GC.Collect()), it's still at 34.29 MB. But after that, I load another fullscreen texture (for the title screen background) and memory usage still doesn't change. Could it be keeping the memory for these textures allocated and reusing it? edit: very simple test: protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); PrintMemUsage("Before texture load: "); // TODO: use this.Content to load your game content here red = this.Content.Load<Texture2D>("Untitled"); PrintMemUsage("After texture load: "); } private void PrintMemUsage(string tag) { Debug.WriteLine(tag + Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage")); } protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // TODO: Add your update logic here if (count++ == 100) { GC.Collect(); GC.WaitForPendingFinalizers(); PrintMemUsage("Before CM unload: "); this.Content.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); PrintMemUsage("After CM unload: "); red = null; spriteBatch.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); PrintMemUsage("After SpriteBatch Dispose(): "); } base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here if (red != null) { spriteBatch.Begin(); spriteBatch.Draw(red, new Vector2(0,0), Color.White); spriteBatch.End(); } base.Draw(gameTime); } This prints something like (it changes every time): Before texture load: 7532544 After texture load: 10727424 Before CM unload: 9875456 After CM unload: 9953280 After SpriteBatch Dispose(): 9953280

    Read the article

  • Why RenderTarget2D overwrites other objects when trying to put some text in a model?

    - by cad
    I am trying to draw an object composited by two cubes (A & B) (one on top of the other, but for now I have them a little bit more open). I am able to do it and this is the result. (Cube A is the blue and Cube B is the one with brown text that comes from a png texture) But I want to have any text as parameter in the cube B. I have tried what @alecnash suggested in his question, but for some reason when I try to draw cube B, cube A dissapears and everything turns purple. This is my draw code: public void Draw(GraphicsDevice graphicsDevice, SpriteBatch spriteBatch, Matrix viewMatrix, Matrix projectionMatrix) { graphicsDevice.BlendState = BlendState.Opaque; graphicsDevice.DepthStencilState = DepthStencilState.Default; graphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise; graphicsDevice.SamplerStates[0] = SamplerState.LinearClamp; // CUBE A basicEffect.View = viewMatrix; basicEffect.Projection = projectionMatrix; basicEffect.World = Matrix.CreateTranslation(ModelPosition); basicEffect.VertexColorEnabled = true; foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) { pass.Apply(); drawCUBE_TOP(graphicsDevice); drawCUBE_Floor(graphicsDevice); DrawFullSquareStripesFront(graphicsDevice, _numStrips, Color.Red, Color.Blue, _levelPercentage); DrawFullSquareStripesLeft(graphicsDevice, _numStrips, Color.Red, Color.Blue, _levelPercentage); DrawFullSquareStripesRight(graphicsDevice, _numStrips, Color.Red, Color.Blue, _levelPercentage); DrawFullSquareStripesBack(graphicsDevice, _numStrips, Color.Red, Color.Blue, _levelPercentage); } // CUBE B // Set the World matrix which defines the position of the cube texturedCubeEffect.World = Matrix.CreateTranslation(ModelPosition); // Set the View matrix which defines the camera and what it's looking at texturedCubeEffect.View = viewMatrix; // Set the Projection matrix which defines how we see the scene (Field of view) texturedCubeEffect.Projection = projectionMatrix; // Enable textures on the Cube Effect. this is necessary to texture the model texturedCubeEffect.TextureEnabled = true; Texture2D a = SpriteFontTextToTexture(graphicsDevice, spriteBatch, arialFont, "TEST ", Color.Black, Color.GhostWhite); texturedCubeEffect.Texture = a; //texturedCubeEffect.Texture = cubeTexture; // Enable some pretty lights texturedCubeEffect.EnableDefaultLighting(); // apply the effect and render the cube foreach (EffectPass pass in texturedCubeEffect.CurrentTechnique.Passes) { pass.Apply(); cubeToDraw.RenderToDevice(graphicsDevice); } } private Texture2D SpriteFontTextToTexture(GraphicsDevice graphicsDevice, SpriteBatch spriteBatch, SpriteFont font, string text, Color backgroundColor, Color textColor) { Vector2 Size = font.MeasureString(text); RenderTarget2D renderTarget = new RenderTarget2D(graphicsDevice, (int)Size.X, (int)Size.Y); graphicsDevice.SetRenderTarget(renderTarget); graphicsDevice.Clear(Color.Transparent); spriteBatch.Begin(); //have to redo the ColorTexture //spriteBatch.Draw(ColorTexture.Create(graphicsDevice, 1024, 1024, backgroundColor), Vector2.Zero, Color.White); spriteBatch.DrawString(font, text, Vector2.Zero, textColor); spriteBatch.End(); graphicsDevice.SetRenderTarget(null); return renderTarget; } The way I generate texture with dynamic text is: Texture2D a = SpriteFontTextToTexture(graphicsDevice, spriteBatch, arialFont, "TEST ", Color.Black, Color.GhostWhite); After commenting several parts to see what caused the problem, it seems to be located in this line graphicsDevice.SetRenderTarget(renderTarget);

    Read the article

  • .NET: Can I use DataContractJsonSerializer to serialize to a JSON associative array?

    - by Cheeso
    When using DataContractJsonSerializer to serialize a dictionary, like so: [CollectionDataContract] public class Clazz : Dictionary<String,String> {} .... var c1 = new Clazz(); c1["Red"] = "Rosso"; c1["Blue"] = "Blu"; c1["Green"] = "Verde"; Serializing c1 with this code: var dcjs = new DataContractJsonSerializer(c1.GetType()); var json = new Func<String>(() => { using (var ms = new System.IO.MemoryStream()) { dcjs.WriteObject(ms, c1); return Encoding.ASCII.GetString(ms.ToArray()); } })(); ...produces this JSON: [{"Key":"Red","Value":"Rosso"}, {"Key":"Blue","Value":"Blu"}, {"Key":"Green","Value":"Verde"}] But, this isn't a Javascript associative array. If I do the corresponding thing in javascript: produce a dictionary and then serialize it, like so: var a = {}; a["Red"] = "Rosso"; a["Blue"] = "Blu"; a["Green"] = "Verde"; // use utility class from http://www.JSON.org/json2.js var json = JSON.stringify(a); The result is: {"Red":"Rosso","Blue":"Blu","Green":"Verde"} How can I get DCJS to produce or consume a serialized string for a dictionary, that is compatible with JSON2.js ? I know about JavaScriptSerializer from ASP.NET. Not sure if it's very WCF friendly. Does it respect DataMember, DataContract attributes?

    Read the article

  • jQuery addClass on $.post

    - by Tim
    I am basically trying to create a small registration form. If the username is already taken, I want to add the 'red' class, if not then 'green'. The PHP here works fine, and returns either a "YES" or "NO" to determine whether it's ok. The CSS: input { border:1px solid #ccc; } .red { border:1px solid #c00; } .green { border:1px solid green; background:#afdfaf; } The Javascript I'm using is: $("#username").change(function() { var value = $("#username").val(); if(value!= '') { $.post("check.php", { value: value }, function(data){ $("#test").html(data); if(data=='YES') { $("#username").removeClass('red').addClass('green'); } if(data=='NO') { $("#username").removeClass('green').addClass('red'); } }); } }); I've got the document.ready stuff too... It all works fine because the #test div html changes to either "YES" or "NO", apart from the last part where I check what the value of the data is. Here is the php: $value=$_POST['value']; if ($value!="") { $sql="select * FROM users WHERE username='".$value."'"; $query = mysql_query($sql) or die ("Could not match data because ".mysql_error()); $num_rows = mysql_num_rows($query); if ($num_rows 0) { echo "NO"; } else { echo "YES"; } }

    Read the article

< Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >