Search Results

Search found 175 results on 7 pages for 'rosarch'.

Page 3/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • C#: Inheritance, Overriding, and Hiding

    - by Rosarch
    I'm having difficulty with an architectural decision for my C# XNA game. The basic entity in the world, such as a tree, zombie, or the player, is represented as a GameObject. Each GameObject is composed of at least a GameObjectController, GameObjectModel, and GameObjectView. These three are enough for simple entities, like inanimate trees or rocks. However, as I try to keep the functionality as factored out as possible, the inheritance begins to feel unwieldy. Syntactically, I'm not even sure how best to accomplish my goals. Here is the GameObjectController: public class GameObjectController { protected GameObjectModel model; protected GameObjectView view; public GameObjectController(GameObjectManager gameObjectManager) { this.gameObjectManager = gameObjectManager; model = new GameObjectModel(this); view = new GameObjectView(this); } public GameObjectManager GameObjectManager { get { return gameObjectManager; } } public virtual GameObjectView View { get { return view; } } public virtual GameObjectModel Model { get { return model; } } public virtual void Update(long tick) { } } I want to specify that each subclass of GameObjectController will have accessible at least a GameObjectView and GameObjectModel. If subclasses are fine using those classes, but perhaps are overriding for a more sophisticated Update() method, I don't want them to have to duplicate the code to produce those dependencies. So, the GameObjectController constructor sets those objects up. However, some objects do want to override the model and view. This is where the trouble comes in. Some objects need to fight, so they are CombatantGameObjects: public class CombatantGameObject : GameObjectController { protected new readonly CombatantGameModel model; public new virtual CombatantGameModel Model { get { return model; } } protected readonly CombatEngine combatEngine; public CombatantGameObject(GameObjectManager gameObjectManager, CombatEngine combatEngine) : base(gameObjectManager) { model = new CombatantGameModel(this); this.combatEngine = combatEngine; } public override void Update(long tick) { if (model.Health <= 0) { gameObjectManager.RemoveFromWorld(this); } base.Update(tick); } } Still pretty simple. Is my use of new to hide instance variables correct? Note that I'm assigning CombatantObjectController.model here, even though GameObjectController.Model was already set. And, combatants don't need any special view functionality, so they leave GameObjectController.View alone. Then I get down to the PlayerController, at which a bug is found. public class PlayerController : CombatantGameObject { private readonly IInputReader inputReader; private new readonly PlayerModel model; public new PlayerModel Model { get { return model; } } private float lastInventoryIndexAt; private float lastThrowAt; public PlayerController(GameObjectManager gameObjectManager, IInputReader inputReader, CombatEngine combatEngine) : base(gameObjectManager, combatEngine) { this.inputReader = inputReader; model = new PlayerModel(this); Model.Health = Constants.PLAYER_HEALTH; } public override void Update(long tick) { if (Model.Health <= 0) { gameObjectManager.RemoveFromWorld(this); for (int i = 0; i < 10; i++) { Debug.WriteLine("YOU DEAD SON!!!"); } return; } UpdateFromInput(tick); // .... } } The first time that this line is executed, I get a null reference exception: model.Body.ApplyImpulse(movementImpulse, model.Position); model.Position looks at model.Body, which is null. This is a function that initializes GameObjects before they are deployed into the world: public void Initialize(GameObjectController controller, IDictionary<string, string> data, WorldState worldState) { controller.View.read(data); controller.View.createSpriteAnimations(data, _assets); controller.Model.read(data); SetUpPhysics(controller, worldState, controller.Model.BoundingCircleRadius, Single.Parse(data["x"]), Single.Parse(data["y"]), bool.Parse(data["isBullet"])); } Every object is passed as a GameObjectController. Does that mean that if the object is really a PlayerController, controller.Model will refer to the base's GameObjectModel and not the PlayerController's overriden PlayerObjectModel? In response to rh: This means that now for a PlayerModel p, p.Model is not equivalent to ((CombatantGameObject)p).Model, and also not equivalent to ((GameObjectController)p).Model. That is exactly what I do not want. I want: PlayerController p; p.Model == ((CombatantGameObject)p).Model p.Model == ((GameObjectController)p).Model How can I do this? override?

    Read the article

  • C#: Windows Forms: What could cause Invalidate() to not redraw?

    - by Rosarch
    I'm using Windows Forms. For a long time, pictureBox.Invalidate(); worked to make the screen be redrawn. However, it now doesn't work and I'm not sure why. this.worldBox = new System.Windows.Forms.PictureBox(); this.worldBox.BackColor = System.Drawing.SystemColors.Control; this.worldBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.worldBox.Location = new System.Drawing.Point(170, 82); this.worldBox.Name = "worldBox"; this.worldBox.Size = new System.Drawing.Size(261, 250); this.worldBox.TabIndex = 0; this.worldBox.TabStop = false; this.worldBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.worldBox_MouseMove); this.worldBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.worldBox_MouseDown); this.worldBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.worldBox_MouseUp); Called in my code to draw the world appropriately: view.DrawWorldBox(worldBox, canvas, gameEngine.GameObjectManager.Controllers, selectedGameObjects, LevelEditorUtils.PREVIEWS); View.DrawWorldBox: public void DrawWorldBox(PictureBox worldBox, Panel canvas, ICollection<IGameObjectController> controllers, ICollection<IGameObjectController> selectedGameObjects, IDictionary<string, Image> previews) { int left = Math.Abs(worldBox.Location.X); int top = Math.Abs(worldBox.Location.Y); Rectangle screenRect = new Rectangle(left, top, canvas.Width, canvas.Height); IDictionary<float, ICollection<IGameObjectController>> layers = LevelEditorUtils.LayersOfControllers(controllers); IOrderedEnumerable<KeyValuePair<float, ICollection<IGameObjectController>>> sortedLayers = from item in layers orderby item.Key descending select item; using (Graphics g = Graphics.FromImage(worldBox.Image)) { foreach (KeyValuePair<float, ICollection<IGameObjectController>> kv in sortedLayers) { foreach (IGameObjectController controller in kv.Value) { // ... float scale = controller.View.Scale; float width = controller.View.Width; float height = controller.View.Height; Rectangle controllerRect = new Rectangle((int)controller.Model.Position.X, (int)controller.Model.Position.Y, (int)(width * scale), (int)(height * scale)); // cull objects that aren't intersecting with the canvas if (controllerRect.IntersectsWith(screenRect)) { Image img = previews[controller.Model.HumanReadableName]; g.DrawImage(img, controllerRect); } if (selectedGameObjects.Contains(controller)) { selectionRectangles.Add(controllerRect); } } } foreach (Rectangle rect in selectionRectangles) { g.DrawRectangle(drawingPen, rect); } selectionRectangles.Clear(); } worldBox.Invalidate(); } What could I be doing wrong here?

    Read the article

  • c#: Clean way to fit a collection into a multidimensional array?

    - by Rosarch
    I have an ICollection<MapNode>. Each MapNode has a Position attribute, which is a Point. I want to sort these points first by Y value, then by X value, and put them in a multidimensional array (MapNode[,]). The collection would look something like this: (30, 20) (20, 20) (20, 30) (30, 10) (30, 30) (20, 10) And the final product: (20, 10) (20, 20) (20, 30) (30, 10) (30, 20) (30, 30) Here is the code I have come up with to do it. Is this hideously unreadable? I feel like it's more hacky than it needs to be. private Map createWorldPathNodes() { ICollection<MapNode> points = new HashSet<MapNode>(); Rectangle worldBounds = WorldQueryUtils.WorldBounds(); for (float x = worldBounds.Left; x < worldBounds.Right; x += PATH_NODE_CHUNK_SIZE) { for (float y = worldBounds.Y; y > worldBounds.Height; y -= PATH_NODE_CHUNK_SIZE) { // default is that everywhere is navigable; // a different function is responsible for determining the real value points.Add(new MapNode(true, new Point((int)x, (int)y))); } } int distinctXValues = points.Select(node => node.Position.X).Distinct().Count(); int distinctYValues = points.Select(node => node.Position.Y).Distinct().Count(); IList<MapNode[]> mapNodeRowsToAdd = new List<MapNode[]>(); while (points.Count > 0) // every iteration will take a row out of points { // get all the nodes with the greatest Y value currently in the collection int currentMaxY = points.Select(node => node.Position.Y).Max(); ICollection<MapNode> ythRow = points.Where(node => node.Position.Y == currentMaxY).ToList(); // remove these nodes from the pool we're picking from points = points.Where(node => ! ythRow.Contains(node)).ToList(); // ToList() is just so it is still a collection // put the nodes with max y value in the array, sorting by X value mapNodeRowsToAdd.Add(ythRow.OrderByDescending(node => node.Position.X).ToArray()); } MapNode[,] mapNodes = new MapNode[distinctXValues, distinctYValues]; int xValuesAdded = 0; int yValuesAdded = 0; foreach (MapNode[] mapNodeRow in mapNodeRowsToAdd) { xValuesAdded = 0; foreach (MapNode node in mapNodeRow) { // [y, x] may seem backwards, but mapNodes[y] == the yth row mapNodes[yValuesAdded, xValuesAdded] = node; xValuesAdded++; } yValuesAdded++; } return pathNodes; } The above function seems to work pretty well, but it hasn't been subjected to bulletproof testing yet.

    Read the article

  • Python: Networked IDLE?

    - by Rosarch
    Is there any existing web app that lets multiple users work with an interactive IDLE type session at once? Something like: IDLE 2.6.4 Morgan: >>> letters = list("abcdefg") Morgan: >>> # now, how would you iterate over letters? Jack: >>> for char in letters: print "char %s" % char char a char b char c char d char e char f char g Morgan: >>> # nice nice If not, I would like to create one. Is there some module I can use that simulates an interactive session? I'd want an interface like this: def class InteractiveSession(): ''' An interactive Python session ''' def putLine(line): ''' Evaluates line ''' pass def outputLines(): ''' A list of all lines that have been output by the session ''' pass def currentVars(): ''' A dictionary of currently defined variables and their values ''' pass (Although that last function would be more of an extra feature.) To formulate my problem another way: I'd like to create a new front end for IDLE. How can I do this?

    Read the article

  • XML: When to use attributes instead of child nodes?

    - by Rosarch
    For tree leaves in XML, when is it better to use attributes, and when is it better to use descendant nodes? For example, in the following XML document: <?xml version="1.0" encoding="utf-8" ?> <savedGame> <links> <link rootTagName="zombies" packageName="zombie" /> <link rootTagName="ghosts" packageName="ghost" /> <link rootTagName="players" packageName="player" /> <link rootTagName="trees" packageName="tree" /> </links> <locations> <zombies> <zombie> <positionX>41</positionX> <positionY>100</positionY> </zombie> <zombie> <positionX>55</positionX> <positionY>56</positionY> </zombie> </zombies> <ghosts> <ghost> <positionX>11</positionX> <positionY>90</positionY> </ghost> </ghosts> </locations> </savedGame> The <link> tag has attributes, but it could also be written as: <link> <rootTagName>trees</rootTagName> <packageName>tree</packageName> </link> Similarly, the location tags could be written as: <zombie positionX="55" positionY="56" /> instead of: <zombie> <positionX>55</positionX> <positionY>56</positionY> </zombie> What reasons are there to prefer one over the other? Is it just a stylistic issue? Any performance considerations?

    Read the article

  • C#: Easy access to the member of a singleton ICollection<> ?

    - by Rosarch
    I have an ICollection that I know will only ever have one member. Currently, I loop through it, knowing the loop will only ever run once, to grab the value. Is there a cleaner way to do this? I could alter the persistentState object to return single values, but that would complicate the rest of the interface. It's grabbing data from XML, and for the most part ICollections are appropriate. // worldMapLinks ensured to be a singleton ICollection<IDictionary<string, string>> worldMapLinks = persistentState.GetAllOfType("worldMapLink"); string levelName = ""; //worldMapLinks.GetEnumerator().Current['filePath']; // this loop will only run once foreach (IDictionary<string, string> dict in worldMapLinks) // hacky hack hack hack { levelName = dict["filePath"]; } // proceed with levelName loadLevel(levelName); Here is another example of the same issue: // meta will be a singleton ICollection<IDictionary<string, string>> meta = persistentState.GetAllOfType("meta"); foreach (IDictionary<string, string> dict in meta) // this loop should only run once. HACKS. { currentLevelName = dict["name"]; currentLevelCaption = dict["teaserCaption"]; } Yet another example: private Vector2 startPositionOfKV(ICollection<IDictionary<string, string>> dicts) { Vector2 result = new Vector2(); foreach (IDictionary<string, string> dict in dicts) // this loop will only ever run once { result.X = Single.Parse(dict["x"]); result.Y = Single.Parse(dict["y"]); } return result; }

    Read the article

  • JavaScript: What would cause setInterval to stop firing?

    - by Rosarch
    I am writing a chat AJAX app. Randomly, in FF 3.5.9, setInterval() seems to stop firing. I don't have clearInterval() anywhere in my code. What could be causing this to happen? $(document).ready(function () { $("#no-js-warning").empty(); messageRefresher = new MessageRefresher(0); setInterval($.proxy(messageRefresher, "refresh"), 2000); }); function notifyInRoom(user) { $.getJSON('API/users_in_room', { room_id: $.getUrlVar('key'), username: user }, function (users) { if (!$.isEmptyObject(users)) { $("#users").empty(); $.each(users, function (index, username) { var newChild = sprintf("<li>%s</li>", username); $("#users").append(newChild); }); } else { $("#users-loading-msg").text("No one is in this room."); } }); } function MessageRefresher(latest_mid) { this._latest_mid = latest_mid; } MessageRefresher.prototype.refresh = function () { notifyInRoom($("#user-name").val()); var refresher = this; $.getJSON('API/read_messages', { room_id: $.getUrlVar('key'), mid: refresher._latest_mid }, function (messages) { if (! (messages == null || $.isEmptyObject(messages[0]))) { // messages will always be at least [[], [], 0] $("#messages-loading-msg").hide(); for (var i = 0; i < messages[0].length; i++) { var newChild = sprintf('<li><span class="username">%s:</span> %s</li>', messages[1][i], messages[0][i]); $("#messages").append(newChild); } refresher._latest_mid = messages[2]; setUserBlockClass(); } else { $("#messages-loading-msg").text("No messages here. Say anything..."); } }); } // Give the end-user-block class to the appropriate messages // eg, those where the next message is by a different user function setUserBlockClass() { $("#messages li").each(function (index) { if ($(this).children(".username").text() != $(this).next().children(".username").text()) { $(this).addClass("end-user-block"); } }); } I checked the most recent responses in Firebug, and it was the same responses that had been sent earlier. (So, it's not like an unusual response caused a crash.) If I refresh the page, the calls resume.

    Read the article

  • Getting started with XSD validation with .NET

    - by Rosarch
    Here is my first attempt at validating XML with XSD. The XML file to be validated: <?xml version="1.0" encoding="utf-8" ?> <config xmlns="Schemas" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="config.xsd"> <levelVariant> <filePath>SampleVariant</filePath> </levelVariant> <levelVariant> <filePath>LegendaryMode</filePath> </levelVariant> <levelVariant> <filePath>AmazingMode</filePath> </levelVariant> </config> The XSD, located in "Schemas/config.xsd" relative to the XML file to be validated: <?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="config"> <xs:complexType> <xs:sequence> <xs:element name="levelVariant"> <xs:complexType> <xs:sequence> <xs:element name="filePath" type="xs:anyURI"> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> Right now, I just want to validate the XML file precisely as it appears currently. Once I understand this better, I'll expand more. Do I really need so many lines for something as simple as the XML file as it currently exists? The validation code in C#: public void SetURI(string uri) { XElement toValidate = XElement.Load(Path.Combine(PATH_TO_DATA_DIR, uri) + ".xml"); // begin confusion // exception here string schemaURI = toValidate.Attributes("xmlns").First().ToString() + toValidate.Attributes("xsi:noNamespaceSchemaLocation").First().ToString(); XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add(null, schemaURI); XDocument toValidateDoc = new XDocument(toValidate); toValidateDoc.Validate(schemas, null); // end confusion root = toValidate; } Running the above code gives this exception: The ':' character, hexadecimal value 0x3A, cannot be included in a name. Any illumination would be appreciated.

    Read the article

  • XNA: Best way to load and read a XML file?

    - by Rosarch
    I'm having difficulty doing this seemingly simple task. I want to load XML files with the same ease of loading art assets: content = new ContentManager(Services); content.RootDirectory = "Content"; Texture2d background = content.Load<Texture2D>("images\\ice"); I'm not sure how to do this. This tutorial seems helpful, but how do I get a StorageDevice instance? I do have something working now, but it feels pretty hacky: public IDictionary<string, string> Get(string typeName) { IDictionary<String, String> result = new Dictionary<String, String>(); xmlReader.Read(); // get past the XML declaration string element = null; string text = null; while (xmlReader.Read()) { switch (xmlReader.NodeType) { case XmlNodeType.Element: element = xmlReader.Name; break; case XmlNodeType.Text: text = xmlReader.Value; break; } if (text != null && element != null) { result[element] = text; text = null; element = null; } } return result; } I apply this to the following XML file: <?xml version="1.0" encoding="utf-8" ?> <zombies> <zombie> <health>100</health> <positionX>23</positionX> <positionY>12</positionY> <speed>2</speed> </zombie> </zombies> And it is able to pass this unit test: internal virtual IPersistentState CreateIPersistentState(string fullpath) { IPersistentState target = new ReadWriteXML(File.Open(fullpath, FileMode.Open)); return target; } /// <summary> ///A test for Get with one zombie. ///</summary> //[TestMethod()] public void SimpleGetTest() { string fullPath = "C:\\pathTo\\Data\\SavedZombies.xml"; IPersistentState target = CreateIPersistentState(fullPath); string typeName = "zombie"; IDictionary<string, string> expected = new Dictionary<string, string>(); expected["health"] = "100"; expected["positionX"] = "23"; expected["positionY"] = "12"; expected["speed"] = "2"; IDictionary<string, string> actual = target.Get(typeName); foreach (KeyValuePair<string, string> entry in expected) { Assert.AreEqual(entry.Value, expected[entry.Key]); } } Downsides to the current approach: file loading is done poorly, and matching keys to values seems like it's way more effort than necessary. Also, I suspect this approach would fall apart with more than one entry in the XML. I can't imagine that this is the optimal implementation.

    Read the article

  • Visual Studio 2010 Formatting

    - by Rosarch
    I have plenty of experience with Eclipse, and now I'm trying out Visual Studio 2010. I find its formatting somewhat counter-intuitive. Here are some things I'm trying to figure out: Is there a way to select all text and format/indent it properly, like SHIFT+A SHIFT+I in Eclipse? Why is it that when I type a line like if (n == 0) {, as soon as I type the opening brace, the text cursor is moved to the beginning of the line? Is this some productivity speedup I'm failing to see? When I hit ENTER after the aforementioned line, I'd like the closing brace to be put in place automatically for me. How can I do this? I've looked for hotkey documentation, and it's helped a bit, but this still feels clunky to me.

    Read the article

  • jQuery tooltip: Trouble with remove()

    - by Rosarch
    I'm using a jQuery tooltip plugin. I have HTML like this: <li class="term ui-droppable"> <strong>Fall 2011</strong> <li class="course ui-draggable">Biological Statistics I<a class="remove-course-button" href="">[X]</a></li> <div class="term-meta-data"> <p class="total-credits too-few-credits">Total credits: 3</p> <p class="median-GPA low-GPA">Median Historical GPA: 2.00</p> </div> </li> I want to remove the .course element. So, I attach a click handler to the <a>: function _addDeleteButton(course, term) { var delete_button = $('<a href="" class="remove-course-button" title="Remove this course">[X]</a>'); course.append(delete_button); $(delete_button).click(function() { course.remove(); return false; }).tooltip(); } This all works fine, in terms of attaching the click handler. However, when course.remove() is called, Firebug reports an error in tooltip.js: Line 282 tsettings is null if ((!IE || !$.fn.bgiframe) && tsettings.fade) { What am I doing wrong? If the link has a tooltip attached, do I need to remove it specially? UPDATE: Removing .tooltip() solve the problem. I'd like to keep it in, but that makes me suspect that my use of .tooltip() is incorrect here.

    Read the article

  • C#: How to remove items from the collection of a IDictionary<E, ICollection<T>> with LINQ?

    - by Rosarch
    Here is what I am trying to do: private readonly IDictionary<float, ICollection<IGameObjectController>> layers; foreach (ICollection<IGameObjectController> layerSet in layers.Values) { foreach (IGameObjectController controller in layerSet) { if (controller.Model.DefinedInVariant) { layerSet.Remove(controller); } } } Of course, this doesn't work, because it will cause a concurrent modification exception. (Is there an equivalent of Java's safe removal operation on some iterators?) How can I do this correctly, or with LINQ?

    Read the article

  • Python/PyParsing: Difficulty with setResultsName

    - by Rosarch
    I think I'm making a mistake in how I call setResultsName(): from pyparsing import * DEPT_CODE = Regex(r'[A-Z]{2,}').setResultsName("Dept Code") COURSE_NUMBER = Regex(r'[0-9]{4}').setResultsName("Course Number") COURSE_NUMBER.setParseAction(lambda s, l, toks : int(toks[0])) course = DEPT_CODE + COURSE_NUMBER course.setResultsName("course") statement = course From IDLE: >>> myparser import * >>> statement.parseString("CS 2110") (['CS', 2110], {'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}) The output I hope for: >>> myparser import * >>> statement.parseString("CS 2110") (['CS', 2110], {'Course': ['CS', 2110], 'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}) Does setResultsName() only work for terminals?

    Read the article

  • Python: needs more than 1 value to unpack

    - by Rosarch
    What am I doing wrong to get this error? replacements = {} replacements["**"] = ("<strong>", "</strong>") replacements["__"] = ("<em>", "</em>") replacements["--"] = ("<blink>", "</blink>") replacements["=="] = ("<marquee>", "</marquee>") replacements["@@"] = ("<code>", "</code>") for delimiter, (open_tag, close_tag) in replacements: # error here message = self.replaceFormatting(delimiter, message, open_tag, close_tag); The error: Traceback (most recent call last): File "", line 1, in for shit, (a, b) in replacements: ValueError: need more than 1 value to unpack All the values tuples have two values. Right?

    Read the article

  • Python/YACC: Resolving a shift/reduce conflict

    - by Rosarch
    I'm using PLY. Here is one of my states from parser.out: state 3 (5) course_data -> course . (6) course_data -> course . course_list_tail (3) or_phrase -> course . OR_CONJ COURSE_NUMBER (7) course_list_tail -> . , COURSE_NUMBER (8) course_list_tail -> . , COURSE_NUMBER course_list_tail ! shift/reduce conflict for OR_CONJ resolved as shift $end reduce using rule 5 (course_data -> course .) OR_CONJ shift and go to state 7 , shift and go to state 8 ! OR_CONJ [ reduce using rule 5 (course_data -> course .) ] course_list_tail shift and go to state 9 I want to resolve this as: if OR_CONJ is followed by COURSE_NUMBER: shift and go to state 7 else: reduce using rule 5 (course_data -> course .) How can I fix my parser file to reflect this? Do I need to handle a syntax error by backtracking and trying a different rule?

    Read the article

  • jQuery: Can't get tooltip plugin to work

    - by Rosarch
    I'm trying to use this tooltip plugin: http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/. I can't seem to get it to work. <head> <script type="text/javascript" src="/static/JQuery.js"></script> <script type="text/javascript" src="/static/jquery-ui-1.8.1.custom.min.js"></script> <script type="text/javascript" src="/static/jquery.json-2.2.min.js"></script> <script type="text/javascript" src="/static/jquery.form.js"></script> <script type="text/javascript" src="/static/js-lib/jquery.bgiframe.js"></script> <script type="text/javascript" src="/static/js-lib/jquery.delegate.js"></script> <script type="text/javascript" src="/static/js-lib/jquery.dimensions.js"></script> <script type="text/javascript" src="/static/jquery.tooltip.js"></script> <script type="text/javascript" src="/static/sprintf.js"></script> <script type="text/javascript" src="/static/clientside.js"></script> </head> I try it out in a simple example: clientside.js: $(document).ready(function () { $("#set1 *").tooltip(); }); The target html: <div id="set1"> <p id="welcome">Welcome. What is your email?</p> <form id="form-username-form" action="api/user_of_email" method="get"> <p> <label for="form-username">Email:</label> <input type="text" name="email" id="form-username" /> <input type="submit" value="Submit" id="form-submit" /> </p> </form> <p id="msg-user-accepted"></p> </div> Unfortunately, nothing happens. What am I doing wrong?

    Read the article

  • C#: Get a list of every value for a given key in a set of dictionaries?

    - by Rosarch
    How can I write this code more cleanly/concisely? /// <summary> /// Creates a set of valid URIs. /// </summary> /// <param name="levelVariantURIDicts">A collection of dictionaries of the form: /// dict["filePath"] == theFilePath </param> /// <returns></returns> private ICollection<string> URIsOfDicts(ICollection<IDictionary<string, string>> levelVariantURIDicts) { ICollection<string> result = new HashSet<string>(); foreach (IDictionary<string, string> dict in levelVariantURIDicts) { result.Add(dict["filePath"]); } return result; }

    Read the article

  • Box2dx: Cancel force on a body?

    - by Rosarch
    I'm doing pathfinding where I use force to push body to waypoints. However, once they get close enough to the waypoint, I want to cancel out the force. How can I do this? Do I need to maintain separately all the forces I've applied to the body in question? I'm using Box2dx (C#/XNA). Here is my attempt, but it doesn't work at all: internal PathProgressionStatus MoveAlongPath(PositionUpdater posUpdater) { Vector2 nextGoal = posUpdater.Goals.Peek(); Vector2 currPos = posUpdater.Model.Body.Position; float distanceToNextGoal = Vector2.Distance(currPos, nextGoal); bool isAtGoal = distanceToNextGoal < PROXIMITY_THRESHOLD; Vector2 forceToApply = new Vector2(); double angleToGoal = Math.Atan2(nextGoal.Y - currPos.Y, nextGoal.X - currPos.X); forceToApply.X = (float)Math.Cos(angleToGoal) * posUpdater.Speed; forceToApply.Y = (float)Math.Sin(angleToGoal) * posUpdater.Speed; float rotation = (float)(angleToGoal + Math.PI / 2); posUpdater.Model.Body.Rotation = rotation; if (!isAtGoal) { posUpdater.Model.Body.ApplyForce(forceToApply, posUpdater.Model.Body.Position); posUpdater.forcedTowardsGoal = true; } if (isAtGoal) { // how can the body be stopped? posUpdater.forcedTowardsGoal = false; //posUpdater.Model.Body.SetLinearVelocity(new Vector2(0, 0)); //posUpdater.Model.Body.ApplyForce(-forceToApply, posUpdater.Model.Body.GetPosition()); posUpdater.Goals.Dequeue(); if (posUpdater.Goals.Count == 0) { return PathProgressionStatus.COMPLETE; } } UPDATE If I do keep track of how much force I've applied, it fails to account for other forces that may act on it. I could use reflection and set _force to zero directly, but that feels dirty.

    Read the article

  • jQuery: Trouble inserting DOM elements

    - by Rosarch
    I want to add a set of lists to the children of another DOM element: var req_subsets = $("#req_subsets"); $.each(subsets, function(index, subset) { var subset_list = $("<ul></ul>"); // add DOM elements to subset_list req_subsets.append(subset_list); }); However, only one DOM element is ever added. This makes me suspect that when I assign a new value to subset_list, the old one is overwritten. If that is the problem, how do I avoid it? If not, what else am I doing wrong? UPDATE: I changed something else, and I'm almost entirely certain that this is fixed.

    Read the article

  • RichEdit control: Determine when text is changed?

    - by Rosarch
    I'm trying to count the number of times that text is changed in a given RichEdit control. I considered using events like key down, but that gets messy when you consider keys that don't change the text (like arrows, page up, etc). And how do you make sure you get all of those keys? It seems it would be simpler to register a callback for a onTextChanged event, if one exists. Is there any way to do something like that?

    Read the article

  • Javascript: Uncaught exception: "too few args"

    - by Rosarch
    I think I must be making some really stupid mistake. I'm using the latest version of jQuery to write an AJAX app. function refreshGPAForTerm(term) { var meta_data = term.children('.' + TERM_META_DATA_CLASS); meta_data.children('.' + MEDIAN_GPA_CLASS).fadeOut('slow').remove(); meta_data.append(_getMedianGPAElem(term.data('GPA'))).hide().fadeIn('slow'); } function moveToTerm(original_course, helper, term) { var cloned_course = original_course.clone(true); term.data('credits', term.data('credits') + cloned_course.data('credits')); term.data('median_GPA', term.data('median_GPA') + cloned_course.data('credits') * cloned_course.data('GPA')); // error here refreshGPAForTerm(term); refreshCreditForTerm(term); original_course.addClass('already-scheduled'); original_course.draggable('disable'); cloned_course.appendTo(term).hide().fadeIn('slow').draggable(); } When refreshGPAForTerm(term) is called, Firebug displays: "Uncaught exception - Too few arguments". Stepping through in a debugger, the code then goes into jQuery. Why is this happening? What am I doing wrong?

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >