Search Results

Search found 1313 results on 53 pages for 'distance'.

Page 14/53 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • Collision detection of huge number of circles

    - by Tomek Tarczynski
    What is the best way to check collision of huge number of circles? It's very easy to detect collision between two circles, but if we check every combination then it is O(n^2) which definitely not an optimal solution. We can assume that circle object has following properties: -Coordinates -Radius -Velocity -Direction Velocity is constant, but direction can change. I've come up with two solutions, but maybe there are some better solutions. Solution 1 Divide whole space into overlapping squares and check for collision only with circles that are in the same square. Squares needs to overlap so there won't be a problem when circle moves from one square to another. Solution 2 At the beginning distances between every pair of circles need to be calculated. If the distance is small then these pair is stored in some list, and we need to check for collision in every update. If the distance is big then we store after which update there can be a collision (it can be calculated because we know the distance and velocitites). It needs to be stored in some kind of priority queue. After previously calculated number of updates distance needs to be checked again and then we do the same procedure - put it on the list or again in the priority queue.

    Read the article

  • Converting from Latitude/Longitude to Cartesian Coordinates with a World File and map image.

    - by Heath
    I have a java applet that allows users to import a jpeg and world file from the local system. The user can then "click" draw lines on the image that was imported. Each endpoint of each line contains a set of X/Y and Lat/Long values. The XY is standard java coordinate space, the applet uses an affine transform calculation with the world file to determine the lat/long for every point on the canvas. I have a requirement that allows a user to type a distance into a text field and use the arrow key to draw a line in a certain direction (Up, Down, Left, Right) from a single selected point on the screen. I know how to determine the lat/long of a point given a source lat/long, distance, and bearing. So a user types "100" in the text field and presses the Right arrow key a line should be drawn 100 feet to the right from the currently selected point. My issue is I don't know how to convert the distance( which is in feet ) into the distance in pixels. This would then tell my where to plot the point.

    Read the article

  • Calculate car filled up times

    - by Ivan
    Here is the question: The driving distance between Perth and Adelaide is 1996 miles. On the average, the fuel consumption of a 2.0 litre 4 cylinder car is 8 litres per 100 kilometres. The fuel tank capacity of such a car is 60 litres. Design and implement a JAVA program that prompts for the fuel consumption and fuel tank capacity of the aforementioned car. The program then displays the minimum number of times the car’s fuel tank has to be filled up to drive from Perth to Adelaide. Note that 62 miles is equal to 100 kilometres. What data will you use to test that your algorithm works correctly? Here is what I've done so far: import java.util.Scanner;// public class Ex4{ public static void main( String args[] ){ Scanner input = new Scanner( System.in ); double distance, consumption, capacity, time; distance = Math.sqrt(1996/62*100); consumption = Math.sqrt(8/100); capacity = 60; time = Math.sqrt(distance*consumption/capacity); System.out.println("The car's fuel tank need to be filled up:" + time + "times"); } } I can compile it but the problem is that the result is always 0.0, can anyone help me what's wrong with it ?

    Read the article

  • Save all xml nodes to db without looping through it

    - by AndreMiranda
    I have this xml: <Path> <Record> <ID>6534808</ID> <Distance>1.05553036073736</Distance> </Record> <Record> <ID>6542471</ID> <Distance>1.05553036073736</Distance> </Record> ... and about more 500 nodes </Path> And I'm using the code below to get all "Record" nodes: XmlNodeList paths = xDoc.SelectNodes("//Record"); And, after that, I save each record to database. But, the problem is that I'm using a foreach to loop through this nodes and the count of this nodes may be more than 500, sometimes it gets up to 1000 "Records" node. And this gets too long... Is there a way to save all of these nodes without looping through it? Thanks!!

    Read the article

  • Why does adding Crossover to my Genetic Algorithm gives me worse results?

    - by MahlerFive
    I have implemented a Genetic Algorithm to solve the Traveling Salesman Problem (TSP). When I use only mutation, I find better solutions than when I add in crossover. I know that normal crossover methods do not work for TSP, so I implemented both the Ordered Crossover and the PMX Crossover methods, and both suffer from bad results. Here are the other parameters I'm using: Mutation: Single Swap Mutation or Inverted Subsequence Mutation (as described by Tiendil here) with mutation rates tested between 1% and 25%. Selection: Roulette Wheel Selection Fitness function: 1 / distance of tour Population size: Tested 100, 200, 500, I also run the GA 5 times so that I have a variety of starting populations. Stop Condition: 2500 generations With the same dataset of 26 points, I usually get results of about 500-600 distance using purely mutation with high mutation rates. When adding crossover my results are usually in the 800 distance range. The other confusing thing is that I have also implemented a very simple Hill-Climbing algorithm to solve the problem and when I run that 1000 times (faster than running the GA 5 times) I get results around 410-450 distance, and I would expect to get better results using a GA. Any ideas as to why my GA performing worse when I add crossover? And why is it performing much worse than a simple Hill-Climb algorithm which should get stuck on local maxima as it has no way of exploring once it finds a local max?

    Read the article

  • Combining multiple rows into one row, Oracle

    - by Torbjørn
    Hi. I'm working with a database which is created in Oracle and used in a GIS-software through SDE. One of my colleuges is going to make some statistics out of this database and I'm not capable of finding a reasonable SQL-query for getting the data. I have two tables, one with registrations and one with registrationdetails. It's a one to many relationship, so the registration can have one or more details connected to it (no maximum number). table: Registration RegistrationID Date TotLenght 1 01.01.2010 5 2 01.02.2010 15 3 05.02.2009 10 2.table: RegistrationDetail DetailID RegistrationID Owner Type Distance 1 1 TD UB 1,5 2 1 AB US 2 3 1 TD UQ 4 4 2 AB UQ 13 5 2 AB UR 13,1 6 3 TD US 5 I want the resulting selection to be something like this: RegistrationID Date TotLenght DetailID RegistrationID Owner Type Distance DetailID RegistrationID Owner Type Distance DetailID RegistrationID Owner Type Distance 1 01.01.2010 5 1 1 TD UB 1,5 2 1 AB US 2 3 1 TD UQ 4 2 01.02.2010 15 4 2 AB UQ 13 5 2 AB UR 13,1 3 05.02.2009 10 6 3 TD US 5 With a normal join I get one row per each registration and detail. Can anyone help me with this? I don't have administrator-rights for the database, so I can't create any tables or variables. If it's possible, I could copy the tables into Access.

    Read the article

  • Is this a variation of the traveling salesman problem?

    - by Ville Koskinen
    I'm interested in a function of two word lists, which would return an order agnostic edit distance between them. That is, the arguments would be two lists of (let's say space delimited) words and return value would be the minimum sum of the edit (or Levenshtein) distances of the words in the lists. Distance between "cat rat bat" and "rat bat cat" would be 0. Distance between "cat rat bat" and "fat had bad" would be the same as distance between "rat bat cat" and "had fat bad", 4. In the case the number of words in the lists are not the same, the shorter list would be padded with 0-length words. My intuition (which hasn't been nurtured with computer science classes) does not find any other solution than to use brute force: |had|fat|bad| a solution ---+---+---+---+ +---+---+---+ cat| 2 | 1 | 2 | | | 1 | | ---+---+---+---+ +---+---+---+ rat| 2 | 1 | 2 | | 3 | | | ---+---+---+---+ +---+---+---+ bat| 2 | 1 | 1 | | | | 4 | ---+---+---+---+ +---+---+---+ Starting from the first row, pick a column and go to the next rows without ever revisiting a column you have already visited. Do this over and over again until you've tried all combinations. To me this sounds a bit like the traveling salesman problem. Is it, and how would you solve my particular problem?

    Read the article

  • Why does adding Crossover to my Genetic Algorithm give me worse results?

    - by MahlerFive
    I have implemented a Genetic Algorithm to solve the Traveling Salesman Problem (TSP). When I use only mutation, I find better solutions than when I add in crossover. I know that normal crossover methods do not work for TSP, so I implemented both the Ordered Crossover and the PMX Crossover methods, and both suffer from bad results. Here are the other parameters I'm using: Mutation: Single Swap Mutation or Inverted Subsequence Mutation (as described by Tiendil here) with mutation rates tested between 1% and 25%. Selection: Roulette Wheel Selection Fitness function: 1 / distance of tour Population size: Tested 100, 200, 500, I also run the GA 5 times so that I have a variety of starting populations. Stop Condition: 2500 generations With the same dataset of 26 points, I usually get results of about 500-600 distance using purely mutation with high mutation rates. When adding crossover my results are usually in the 800 distance range. The other confusing thing is that I have also implemented a very simple Hill-Climbing algorithm to solve the problem and when I run that 1000 times (faster than running the GA 5 times) I get results around 410-450 distance, and I would expect to get better results using a GA. Any ideas as to why my GA performing worse when I add crossover? And why is it performing much worse than a simple Hill-Climb algorithm which should get stuck on local maxima as it has no way of exploring once it finds a local max?

    Read the article

  • Hibernate design to speed up querying of large dataset

    - by paddydub
    I currently have the below tables representing a bus network mapped in hibernate, accessed from a Spring MVC based bus route planner I'm trying to make my route planner application perform faster, I load all the above tables into Lists to perform the route planner logic. I would appreciate if anyone has any ideas of how to speed my performace Or any suggestions of another method to approach this problem of handling a large set of data Coordinate Connections Table (INT,INT,INT, DOUBLE)( Containing 50,000 Coordinate Connections) ID, FROMCOORDID, TOCOORDID, DISTANCE 1 1 2 0.383657 2 1 17 0.173201 3 1 63 0.258781 4 1 64 0.013726 5 1 65 0.459829 6 1 95 0.458769 Coordinate Table (INT,DECIMAL, DECIMAL) (Containing 4700 Coordinates) ID , LAT, LNG 0 59.352669 -7.264341 1 59.352669 -7.264341 2 59.350012 -7.260653 3 59.337585 -7.189798 4 59.339221 -7.193582 5 59.341408 -7.205888 Bus Stop Table (INT, INT, INT)(Containing 15000 Stops) StopID RouteID COORDINATEID 1000100001 100 17 1000100002 100 18 1000100003 100 19 1000100004 100 20 1000100005 100 21 1000100006 100 22 1000100007 100 23 This is how long it takes to load all the data from each table: stop.findAll = 148ms, stops.size: 15670 Hibernate: select coordinate0_.COORDINATEID as COORDINA1_2_, coordinate0_.LAT as LAT2_, coordinate0_.LNG as LNG2_ from COORDINATES coordinate0_ coord.findAll = 51ms , coordinates.size: 4704 Hibernate: select coordconne0_.COORDCONNECTIONID as COORDCON1_3_, coordconne0_.DISTANCE as DISTANCE3_, coordconne0_.FROMCOORDID as FROMCOOR3_3_, coordconne0_.TOCOORDID as TOCOORDID3_ from COORDCONNECTIONS coordconne0_ coordinateConnectionDao.findAll = 238ms ; coordConnectioninates.size:48132 Hibernate Annotations @Entity @Table(name = "STOPS") public class Stop implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "STOPID") private int stopID; @Column(name = "ROUTEID", nullable = false) private int routeID; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "COORDINATEID", nullable = false) private Coordinate coordinate; } @Table(name = "COORDINATES") public class Coordinate { @Id @GeneratedValue @Column(name = "COORDINATEID") private int CoordinateID; @Column(name = "LAT") private double latitude; @Column(name = "LNG") private double longitude; } @Entity @Table(name = "COORDCONNECTIONS") public class CoordConnection { @Id @GeneratedValue @Column(name = "COORDCONNECTIONID") private int CoordinateID; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "FROMCOORDID", nullable = false) private Coordinate fromCoordID; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "TOCOORDID", nullable = false) private Coordinate toCoordID; @Column(name = "DISTANCE", nullable = false) private double distance; }

    Read the article

  • How toget a list of "fastest miles" from a set of GPS Points

    - by santiagobasulto
    I'm trying to solve a weird problem. Maybe you guys know of some algorithm that takes care of this. I have data for a cargo freight truck and want to extract some data. Suppose I've got a list of sorted points that I get from the GPS. That's the route for that truck: [ { "lng": "-111.5373066", "lat": "40.7231711", "time": "1970-01-01T00:00:04Z", "elev": "1942.1789265256325" }, { "lng": "-111.5372056", "lat": "40.7228762", "time": "1970-01-01T00:00:07Z", "elev": "1942.109892409177" } ] Now, what I want to get is a list of the "fastest miles". I'll do an example: Given the points: A, B, C, D, E, F the distance from point A to point B is 1 mile, and the cargo took 10:32 minutes. From point B to point D i've got other mile, and the cargo took 10 minutes, etc. So, i need a list sorted by time. Similar to: B -> D: 10 A -> B: 10:32 D -> F: 11:02 Do you know any efficient algorithm that let me calculate that? Thank you all. PS: I'm using Python. EDIT: I've got the distance. I know how to calculate it and there are plenty of posts to do that. What I need is an algorithm to tokenize by mile and get speed from that. Having a distance function is not helpful enough: results = {} for point in points: aux_points = points.takeWhile(point>n) #This doesn't exist, just trying to be simple for aux_point in aux_points: d = distance(point, aux_point) if d == 1_MILE: time_elapsed = time(point, aux_point) results[time_elapsed] = (point, aux_point) I'm still doing some pretty inefficient calculations.

    Read the article

  • Manhattan Heuristic function for A-star (A*)

    - by Shawn Mclean
    I found this algorithm here. I have a problem, I cant seem to understand how to set up and pass my heuristic function. static public Path<TNode> AStar<TNode>(TNode start, TNode destination, Func<TNode, TNode, double> distance, Func<TNode, double> estimate) where TNode : IHasNeighbours<TNode> { var closed = new HashSet<TNode>(); var queue = new PriorityQueue<double, Path<TNode>>(); queue.Enqueue(0, new Path<TNode>(start)); while (!queue.IsEmpty) { var path = queue.Dequeue(); if (closed.Contains(path.LastStep)) continue; if (path.LastStep.Equals(destination)) return path; closed.Add(path.LastStep); foreach (TNode n in path.LastStep.Neighbours) { double d = distance(path.LastStep, n); var newPath = path.AddStep(n, d); queue.Enqueue(newPath.TotalCost + estimate(n), newPath); } } return null; } As you can see, it accepts 2 functions, a distance and a estimate function. Using the Manhattan Heuristic Distance function, I need to take 2 parameters. Do I need to modify his source and change it to accepting 2 parameters of TNode so I can pass a Manhattan estimate to it? This means the 4th param will look like this: Func<TNode, TNode, double> estimate) where TNode : IHasNeighbours<TNode> and change the estimate function to: queue.Enqueue(newPath.TotalCost + estimate(n, path.LastStep), newPath); My Manhattan function is: private float manhattanHeuristic(Vector3 newNode, Vector3 end) { return (Math.Abs(newNode.X - end.X) + Math.Abs(newNode.Y - end.Y)); }

    Read the article

  • How to use MySQL geospatial extensions with spherical geometries

    - by Joshua
    Hi Everyone, I would like to store thousands of latitude/longitude points in a MySQL db. I was successful at setting up the tables and adding the data using the geospatial extensions where the column 'coord' is a Point(lat, lng). Problem: I want to quickly find the 'N' closest entries to latitude 'X' degrees and longitude 'Y' degrees. Since the Distance() function has not yet been implemented, I used GLength() function to calculate the distance between (X,Y) and each of the entries, sorting by ascending distance, and limiting to 'N' results. The problem is that this is not calculating shortest distance with spherical geometry. Which means if Y = 179.9 degrees, the list of closest entries will only include longitudes of starting at 179.9 and decreasing even though closer entries exist with longitudes increasing from -179.9. How does one typically handle the discontinuity in longitude when working with spherical geometries in databases? There has to be an easy solution to this, but I must just be searching for the wrong thing because I have not found anything helpful. Should I just forget the GLength() function and create my own function for calculating angular separation? If I do this, will it still be fast and take advantage of the geospatial extensions? Thanks! josh UPDATE: This is exactly what I am describing above. However, it is only for SQL Server. Apparently SQL Server has a Geometry and Geography datatypes. The geography does exactly what I need. Is there something similar in MySQL?

    Read the article

  • Android: Find coordinates of a certain point X meters from my location moving towards the point I am

    - by Aidan
    Hi Guys, I'm constructing a geolocation based application and I'm trying to figure out a way to make my application realise when a user is facing the direction of the given location (a particular long / lat co-ord). I've done some Googling and checked the SDK but can't really find anything for such a thing. Does anyone know of a way? Example. Point A = Phones current location. Point B = A's orientation in relation to true north + 45 + max distance towards the direction your facing, Point C = A's orientation in relation to true north - 45 + max distance towards the direction your facing. So now you have a triangle constructed. pretty schweet huh? yeah.. I think so.. So now that I have my fancy Triangle I use something called Barycentric Coordinates ( http://en.wikipedia.org/wiki/Barycentric_coordinates_(mathematics) ). This will allow me to test another point and see if it is in the triangle. If it is, it means we're facing it AND it's within the right distance. So it should be displayed on screen. If I'm facing 90 degrees from true north. The distance it travels should be that direction. 90 degrees from true north. It should not be 100 degrees or something from true north! But the problem is I haven't yet figured out how I make the device realise it must go "out" the direction it is facing.

    Read the article

  • Triangulation in 3D Space

    - by w3b_wizzard
    Disclaimer: This is for class, however I'm fresh out of ideas and a nudge in the right direction would be much appreciated. Also, this needs to be implemented in raw C, so no fancy libraries can be used. I have to write a search and rescue simulator for submarines, it has to find a probe that is randomly placed in 3D space in a grid from of the MAX_XYZ (100000). The only tools I'm given are a "ping" which will give the magnitude of the distance between a certain sub and the probe. The goal is to optimize the costs of this entire operation so a brute force attempt, like looking at every single coordinate, won't work. Hence I was thinking triangulation. Now, it makes loads of sense to me, place three subs, each one of them uses their ping to get the distance between them and the probe. Since each sub have a known distance relative to one another, it's easy to build the base of a tetrahedron with them, and the results of the ping will point to a certain coordinate, the problem I'm having is how to figure out the elevation, or the height, of the tetrahedron. So what I have as data is the following: Distances between subs (In vector format) Angles between each subs (very easy to compute) Distance between each sub and the probe (3 segments from the base to the peak) Angles inside each of the outer 3 surfaces of the tetrahedron. I tried finding some sort of relationship with the vertices of the tetrahedron and the relative angles in each of them, however all I found had to deal with tetrahedrons built with equilateral triangles, which isn't much help. I have the impression this can be easily solved with trig but either I'm not seeing it or I need more coffee. Any suggestions would be appreciated!

    Read the article

  • Text being printed twice in uitableview

    - by user337174
    I have created a uitableview that calculates the distance of a location in the table. I used this code in cell for row at index path. NSString *lat1 = [object valueForKey:@"Lat"]; NSLog(@"Current Spot Latitude:%@",lat1); float lat2 = [lat1 floatValue]; NSLog(@"Current Spot Latitude Float:%g", lat2); NSString *long1 = [object valueForKey:@"Lon"]; NSLog(@"Current Spot Longitude:%@",long1); float long2 = [long1 floatValue]; NSLog(@"Current Spot Longitude Float:%g", long2); //Getting current location from NSDictionary CoreDataTestAppDelegate *appDelegate = (CoreDataTestAppDelegate *) [[UIApplication sharedApplication] delegate]; NSString *locLat = [NSString stringWithFormat:appDelegate.latitude]; float locLat2 = [locLat floatValue]; NSLog(@"Lat: %g",locLat2); NSString *locLong = [NSString stringWithFormat:appDelegate.longitude]; float locLong2 = [locLong floatValue]; NSLog(@"Long: %g",locLong2); //Location of selected spot CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2]; //Current Location CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:locLat2 longitude:locLong2]; double distance = [loc1 getDistanceFrom: loc2] / 1600; NSMutableString* converted = [NSMutableString stringWithFormat:@"%.1f", distance]; [converted appendString: @" m"]; It works fine apart from a problem i have just discovered where the distance text is duplicated over the top of the detailed text label when you scroll beyond the height of the page. here's a screen shot of what i mean. Any ideas why its doing this?

    Read the article

  • Find coordinate by angle

    - by George Johnston
    I am developing in application in XNA which draws random paths. Unfortunately, I'm out of touch with graphing, so I'm a bit stuck. My application needs to do the following: Pick a random angle from my origin (0,0), which is simple. Draw a circle in relation to that origin, 16px away (or any distance I specify), at the angle found above. (Excuse my horrible photoshoping) The second circle at (16,16) would represent a 45 degree angle 16 pixels away from my origin. I would like to have a method in which I pass in my distance and angle that returns a point to graph at. i.e. private Point GetCoordinate(float angle, int distance) { // Do something. return new Point(x,y); } I know this is simple, but agian, I'm pretty out of touch with graphing. Any help? Thanks, George

    Read the article

  • Radial Grid Search Algorithm

    - by grey
    I'm sure there's a clean way to do this, but I'm probably not using the right keywords for find it. So let's say I have a grid. Starting from a position on the grid, return all of the grid coordinates that fall within a given distance. So I call something like: getCoordinates( currentPosition, distance ) And for each coordinate, starting from the initial position, add all cardinal directions, and then add the spaces around those and so forth until the distance is reached. I imagine that on a grid this would look like a diamond.

    Read the article

  • How do I select a fixed number of rows for each group?

    - by Maiasaura
    Here is some example data in a mysql table a b distance 15 44 250 94 31 250 30 41 250 6 1 250 95 18 250 72 84 500 14 23 500 55 24 500 95 8 500 59 25 500 40 73 500 65 85 500 32 50 500 31 39 500 22 25 500 37 11 750 98 39 750 15 57 750 9 22 750 14 44 750 69 22 750 62 50 750 89 35 750 67 65 750 74 37 750 52 36 750 66 53 750 82 74 1000 79 22 1000 98 41 1000 How do I query this table such that I get 2 rows per distance selected at random? A successful query will produce something like a b distance 30 41 250 95 18 250 59 25 500 65 85 500 15 57 750 89 35 750 79 22 1000 98 41 1000

    Read the article

  • Table alias -- Unkown column in field list

    - by Jason
    Hi all, I have a sql query which is executing a LEFT JOIN on 2 tables in which some of the columns are ambiguous. I can prefix the joined tables but when I try to prefix one of the columns from the table in the FROM clause, it tells me Unknown column. I even tried giving that table an alias like so ...From points AS p and using "p" to prefix the tables but that didn't work either. Can someone tell me what I'm doing wrong. Here is my query: SELECT point_title, point_url, address, city, state, zip_code, phone, `points`.`lat`, `points`.`longi`, featured, kmlno, image_url, category.title, category_id, point_id, lat, longi, reviews.star_points, reviews.review_id, count(reviews.point_id) as totals FROM (SELECT *, ( 3959 * acos( cos( radians('37.7717185') ) * cos( radians( lat ) ) * cos( radians( longi ) - radians('-122.4438929') ) + sin( radians('37.7717185') ) * sin( radians( lat ) ) ) ) AS distance FROM points HAVING distance < '25') as distResults LEFT JOIN category USING ( category_id ) LEFT JOIN reviews USING ( point_id ) WHERE (point_title LIKE '%Playgrounds%' OR category.title LIKE '%Playgrounds%') GROUP BY point_id ORDER BY totals DESC, distance LIMIT 0 , 10

    Read the article

  • Using Python read specific (column, row) values from a txt file

    - by user2955708
    I would like to read values from a text file until that is a float value. Lets say I have the following file: 14:53:55 Load 300 Speed 200 Distance,m Fz Fx Speed 0.0000 249 4 6.22 0.0002 247 33 16.29 0.0004 246 49 21.02 0.2492 240 115 26.97 0.2494 241 112 21.78 0.2496 240 109 13.09 0.2498 169 79 0.27 Distance,m Fz Fx Speed 0.0000 249 4 7.22 0.0002 247 33 1.29 0.0004 246 49 271.02 0.2492 240 115 26.97 0.2494 241 112 215.78 0.2496 240 109 13.09 0.2498 169 79 0.27 And I need only the values under the first Distance column. So something like skip the first few rows, then read values from the first column while it is float. Thanks your help in advance

    Read the article

  • mysqldb python escaping ? or %s?

    - by asldkncvas
    Dear Everyone, I am currently using mysqldb. What is the correct way to escape strings in mysqldb arguments? Note that E = lambda x: x.encode('utf-8') 1) so my connection is set with charset='utf8'. These are the errors I am getting for these arguments: w1, w2 = u'??', u'??' 1) self.cur.execute("SELECT dist FROM distance WHERE w1=? AND w2=?", (E(w1), E(w2))) ret = self.cur.execute("SELECT dist FROM distance WHERE w1=? AND w2=?", (E(w1), E(w2)) ) File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 158, in execute TypeError: not all arguments converted during string formatting 2) self.cur.execute("SELECT dist FROM distance WHERE w1=%s AND w2=%s", (E(w1), E(w2))) This works fine, but when w1 or w2 has \ inside, then the escaping obviously failed. I personally know that %s is not a good method to pass in arguemnts due to injection attacks etc.

    Read the article

  • Point of contact of 2 OBBs?

    - by Milo
    I'm working on the physics for my GTA2-like game so I can learn more about game physics. The collision detection and resolution are working great. I'm now just unsure how to compute the point of contact when I hit a wall. Here is my OBB class: public class OBB2D { private Vector2D projVec = new Vector2D(); private static Vector2D projAVec = new Vector2D(); private static Vector2D projBVec = new Vector2D(); private static Vector2D tempNormal = new Vector2D(); private Vector2D deltaVec = new Vector2D(); // Corners of the box, where 0 is the lower left. private Vector2D corner[] = new Vector2D[4]; private Vector2D center = new Vector2D(); private Vector2D extents = new Vector2D(); private RectF boundingRect = new RectF(); private float angle; //Two edges of the box extended away from corner[0]. private Vector2D axis[] = new Vector2D[2]; private double origin[] = new double[2]; public OBB2D(float centerx, float centery, float w, float h, float angle) { for(int i = 0; i < corner.length; ++i) { corner[i] = new Vector2D(); } for(int i = 0; i < axis.length; ++i) { axis[i] = new Vector2D(); } set(centerx,centery,w,h,angle); } public OBB2D(float left, float top, float width, float height) { for(int i = 0; i < corner.length; ++i) { corner[i] = new Vector2D(); } for(int i = 0; i < axis.length; ++i) { axis[i] = new Vector2D(); } set(left + (width / 2), top + (height / 2),width,height,0.0f); } public void set(float centerx,float centery,float w, float h,float angle) { float vxx = (float)Math.cos(angle); float vxy = (float)Math.sin(angle); float vyx = (float)-Math.sin(angle); float vyy = (float)Math.cos(angle); vxx *= w / 2; vxy *= (w / 2); vyx *= (h / 2); vyy *= (h / 2); corner[0].x = centerx - vxx - vyx; corner[0].y = centery - vxy - vyy; corner[1].x = centerx + vxx - vyx; corner[1].y = centery + vxy - vyy; corner[2].x = centerx + vxx + vyx; corner[2].y = centery + vxy + vyy; corner[3].x = centerx - vxx + vyx; corner[3].y = centery - vxy + vyy; this.center.x = centerx; this.center.y = centery; this.angle = angle; computeAxes(); extents.x = w / 2; extents.y = h / 2; computeBoundingRect(); } //Updates the axes after the corners move. Assumes the //corners actually form a rectangle. private void computeAxes() { axis[0].x = corner[1].x - corner[0].x; axis[0].y = corner[1].y - corner[0].y; axis[1].x = corner[3].x - corner[0].x; axis[1].y = corner[3].y - corner[0].y; // Make the length of each axis 1/edge length so we know any // dot product must be less than 1 to fall within the edge. for (int a = 0; a < axis.length; ++a) { float l = axis[a].length(); float ll = l * l; axis[a].x = axis[a].x / ll; axis[a].y = axis[a].y / ll; origin[a] = corner[0].dot(axis[a]); } } public void computeBoundingRect() { boundingRect.left = JMath.min(JMath.min(corner[0].x, corner[3].x), JMath.min(corner[1].x, corner[2].x)); boundingRect.top = JMath.min(JMath.min(corner[0].y, corner[1].y),JMath.min(corner[2].y, corner[3].y)); boundingRect.right = JMath.max(JMath.max(corner[1].x, corner[2].x), JMath.max(corner[0].x, corner[3].x)); boundingRect.bottom = JMath.max(JMath.max(corner[2].y, corner[3].y),JMath.max(corner[0].y, corner[1].y)); } public void set(RectF rect) { set(rect.centerX(),rect.centerY(),rect.width(),rect.height(),0.0f); } // Returns true if other overlaps one dimension of this. private boolean overlaps1Way(OBB2D other) { for (int a = 0; a < axis.length; ++a) { double t = other.corner[0].dot(axis[a]); // Find the extent of box 2 on axis a double tMin = t; double tMax = t; for (int c = 1; c < corner.length; ++c) { t = other.corner[c].dot(axis[a]); if (t < tMin) { tMin = t; } else if (t > tMax) { tMax = t; } } // We have to subtract off the origin // See if [tMin, tMax] intersects [0, 1] if ((tMin > 1 + origin[a]) || (tMax < origin[a])) { // There was no intersection along this dimension; // the boxes cannot possibly overlap. return false; } } // There was no dimension along which there is no intersection. // Therefore the boxes overlap. return true; } public void moveTo(float centerx, float centery) { float cx,cy; cx = center.x; cy = center.y; deltaVec.x = centerx - cx; deltaVec.y = centery - cy; for (int c = 0; c < 4; ++c) { corner[c].x += deltaVec.x; corner[c].y += deltaVec.y; } boundingRect.left += deltaVec.x; boundingRect.top += deltaVec.y; boundingRect.right += deltaVec.x; boundingRect.bottom += deltaVec.y; this.center.x = centerx; this.center.y = centery; computeAxes(); } // Returns true if the intersection of the boxes is non-empty. public boolean overlaps(OBB2D other) { if(right() < other.left()) { return false; } if(bottom() < other.top()) { return false; } if(left() > other.right()) { return false; } if(top() > other.bottom()) { return false; } if(other.getAngle() == 0.0f && getAngle() == 0.0f) { return true; } return overlaps1Way(other) && other.overlaps1Way(this); } public Vector2D getCenter() { return center; } public float getWidth() { return extents.x * 2; } public float getHeight() { return extents.y * 2; } public void setAngle(float angle) { set(center.x,center.y,getWidth(),getHeight(),angle); } public float getAngle() { return angle; } public void setSize(float w,float h) { set(center.x,center.y,w,h,angle); } public float left() { return boundingRect.left; } public float right() { return boundingRect.right; } public float bottom() { return boundingRect.bottom; } public float top() { return boundingRect.top; } public RectF getBoundingRect() { return boundingRect; } public boolean overlaps(float left, float top, float right, float bottom) { if(right() < left) { return false; } if(bottom() < top) { return false; } if(left() > right) { return false; } if(top() > bottom) { return false; } return true; } public static float distance(float ax, float ay,float bx, float by) { if (ax < bx) return bx - ay; else return ax - by; } public Vector2D project(float ax, float ay) { projVec.x = Float.MAX_VALUE; projVec.y = Float.MIN_VALUE; for (int i = 0; i < corner.length; ++i) { float dot = Vector2D.dot(corner[i].x,corner[i].y,ax,ay); projVec.x = JMath.min(dot, projVec.x); projVec.y = JMath.max(dot, projVec.y); } return projVec; } public Vector2D getCorner(int c) { return corner[c]; } public int getNumCorners() { return corner.length; } public static float collisionResponse(OBB2D a, OBB2D b, Vector2D outNormal) { float depth = Float.MAX_VALUE; for (int i = 0; i < a.getNumCorners() + b.getNumCorners(); ++i) { Vector2D edgeA; Vector2D edgeB; if(i >= a.getNumCorners()) { edgeA = b.getCorner((i + b.getNumCorners() - 1) % b.getNumCorners()); edgeB = b.getCorner(i % b.getNumCorners()); } else { edgeA = a.getCorner((i + a.getNumCorners() - 1) % a.getNumCorners()); edgeB = a.getCorner(i % a.getNumCorners()); } tempNormal.x = edgeB.x -edgeA.x; tempNormal.y = edgeB.y - edgeA.y; tempNormal.normalize(); projAVec.equals(a.project(tempNormal.x,tempNormal.y)); projBVec.equals(b.project(tempNormal.x,tempNormal.y)); float distance = OBB2D.distance(projAVec.x, projAVec.y,projBVec.x,projBVec.y); if (distance > 0.0f) { return 0.0f; } else { float d = Math.abs(distance); if (d < depth) { depth = d; outNormal.equals(tempNormal); } } } float dx,dy; dx = b.getCenter().x - a.getCenter().x; dy = b.getCenter().y - a.getCenter().y; float dot = Vector2D.dot(dx,dy,outNormal.x,outNormal.y); if(dot > 0) { outNormal.x = -outNormal.x; outNormal.y = -outNormal.y; } return depth; } public Vector2D getMoveDeltaVec() { return deltaVec; } }; Thanks!

    Read the article

  • Smooth terrain rendering

    - by __dominic
    I'm trying to render a smooth terrain with Direct3D. I've got a 50*50 grid with all y values = 0, and a set of 3D points that indicate the location on the grid and depth or height of the "valley" or "hill". I need to make the y values of the grid vertices higher or lower depending on how close they are to each 3D point. Thus, in the end I should have a smooth terrain renderer. I'm not sure at all what way I can do this. I've tried changing the height of the vertices based on the distance to each point just using this basic formula: dist = a² + b² + c² where a, b and c are the x, y, and z distance from a vertex to a 3D point. The result I get with this is not smooth at all. I'm thinking there is probably a better way. Here is a screenshot of what I've got for the moment: https://dl.dropbox.com/u/2562049/terrain.jpg

    Read the article

  • Find Nearest Object

    - by ultifinitus
    I have a fairly sizable game engine created, and I'm adding some needed features, such as this, how do I find the nearest object from a list of points? In this case, I could simply use the Pythagorean theorem to find the distance, and check the results. I know I can't simply add x and y, because that's the distance to the object, if you only took right angle turns. However I'm wondering if there's something else I could do? I also have a collision system, where essentially I turn objects into smaller objects on a smaller grid, kind of like a minimap, and only if objects exist in the same gridspace do I check for collisions, I could do the same thing, only make the gridspace larger to check for closeness. (rather than checking every. single. object) however that would take additional setup in my base class and clutter up the already cluttered object. TL;DR Question: Is there something efficient and accurate that I can use to detect which object is closest, based on a list of points and sizes?

    Read the article

  • Collision detection with curves

    - by paldepind
    I'm working on a 2D game in which I would like to do collision detection between a moving circle and some kind of static curves (maybe Bezier curves). Currently my game features only straight lines as the static geometry and I'm doing the collision detection by calculating the distance from the circle to the lines, and projecting the circle out of the line in case the distance is less than the circles radius. How can I do this kind of collision detection in a relative straightforward way? I know for instance that Box2D features collision detection with Bezier curves. I don't need a full featured collision detection mechanism, just something that can do what I've described.

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >