Search Results

Search found 968 results on 39 pages for 'closest'.

Page 6/39 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • What's the name for a bug that suddenly breaks things but has always been present?

    - by splattered bits
    We had a failure in our software today and after investigating discovered that the failure should have been occurring for weeks, but it waited until this morning to rear its ugly head. Is there an accepted name for such a bug that I can use when referring to it with other programmers? The closest I could find was a Schrödinbug, but I'm don't think it applies, since nobody was inspecting any code. The bug was just lying in wait.

    Read the article

  • SQL Spatial: Getting “nearest” calculations working properly

    - by Rob Farley
    If you’ve ever done spatial work with SQL Server, I hope you’ve come across the ‘nearest’ problem. You have five thousand stores around the world, and you want to identify the one that’s closest to a particular place. Maybe you want the store closest to the LobsterPot office in Adelaide, at -34.925806, 138.605073. Or our new US office, at 42.524929, -87.858244. Or maybe both! You know how to do this. You don’t want to use an aggregate MIN or MAX, because you want the whole row, telling you which store it is. You want to use TOP, and if you want to find the closest store for multiple locations, you use APPLY. Let’s do this (but I’m going to use addresses in AdventureWorks2012, as I don’t have a list of stores). Oh, and before I do, let’s make sure we have a spatial index in place. I’m going to use the default options. CREATE SPATIAL INDEX spin_Address ON Person.Address(SpatialLocation); And my actual query: WITH MyLocations AS (SELECT * FROM (VALUES ('LobsterPot Adelaide', geography::Point(-34.925806, 138.605073, 4326)),                        ('LobsterPot USA', geography::Point(42.524929, -87.858244, 4326))                ) t (Name, Geo)) SELECT l.Name, a.AddressLine1, a.City, s.Name AS [State], c.Name AS Country FROM MyLocations AS l CROSS APPLY (     SELECT TOP (1) *     FROM Person.Address AS ad     ORDER BY l.Geo.STDistance(ad.SpatialLocation)     ) AS a JOIN Person.StateProvince AS s     ON s.StateProvinceID = a.StateProvinceID JOIN Person.CountryRegion AS c     ON c.CountryRegionCode = s.CountryRegionCode ; Great! This is definitely working. I know both those City locations, even if the AddressLine1s don’t quite ring a bell. I’m sure I’ll be able to find them next time I’m in the area. But of course what I’m concerned about from a querying perspective is what’s happened behind the scenes – the execution plan. This isn’t pretty. It’s not using my index. It’s sucking every row out of the Address table TWICE (which sucks), and then it’s sorting them by the distance to find the smallest one. It’s not pretty, and it takes a while. Mind you, I do like the fact that it saw an indexed view it could use for the State and Country details – that’s pretty neat. But yeah – users of my nifty website aren’t going to like how long that query takes. The frustrating thing is that I know that I can use the index to find locations that are within a particular distance of my locations quite easily, and Microsoft recommends this for solving the ‘nearest’ problem, as described at http://msdn.microsoft.com/en-au/library/ff929109.aspx. Now, in the first example on this page, it says that the query there will use the spatial index. But when I run it on my machine, it does nothing of the sort. I’m not particularly impressed. But what we see here is that parallelism has kicked in. In my scenario, it’s split the data up into 4 threads, but it’s still slow, and not using my index. It’s disappointing. But I can persuade it with hints! If I tell it to FORCESEEK, or use my index, or even turn off the parallelism with MAXDOP 1, then I get the index being used, and it’s a thing of beauty! Part of the plan is here: It’s massive, and it’s ugly, and it uses a TVF… but it’s quick. The way it works is to hook into the GeodeticTessellation function, which is essentially finds where the point is, and works out through the spatial index cells that surround it. This then provides a framework to be able to see into the spatial index for the items we want. You can read more about it at http://msdn.microsoft.com/en-us/library/bb895265.aspx#tessellation – including a bunch of pretty diagrams. One of those times when we have a much more complex-looking plan, but just because of the good that’s going on. This tessellation stuff was introduced in SQL Server 2012. But my query isn’t using it. When I try to use the FORCESEEK hint on the Person.Address table, I get the friendly error: Msg 8622, Level 16, State 1, Line 1 Query processor could not produce a query plan because of the hints defined in this query. Resubmit the query without specifying any hints and without using SET FORCEPLAN. And I’m almost tempted to just give up and move back to the old method of checking increasingly large circles around my location. After all, I can even leverage multiple OUTER APPLY clauses just like I did in my recent Lookup post. WITH MyLocations AS (SELECT * FROM (VALUES ('LobsterPot Adelaide', geography::Point(-34.925806, 138.605073, 4326)),                        ('LobsterPot USA', geography::Point(42.524929, -87.858244, 4326))                ) t (Name, Geo)) SELECT     l.Name,     COALESCE(a1.AddressLine1,a2.AddressLine1,a3.AddressLine1),     COALESCE(a1.City,a2.City,a3.City),     s.Name AS [State],     c.Name AS Country FROM MyLocations AS l OUTER APPLY (     SELECT TOP (1) *     FROM Person.Address AS ad     WHERE l.Geo.STDistance(ad.SpatialLocation) < 1000     ORDER BY l.Geo.STDistance(ad.SpatialLocation)     ) AS a1 OUTER APPLY (     SELECT TOP (1) *     FROM Person.Address AS ad     WHERE l.Geo.STDistance(ad.SpatialLocation) < 5000     AND a1.AddressID IS NULL     ORDER BY l.Geo.STDistance(ad.SpatialLocation)     ) AS a2 OUTER APPLY (     SELECT TOP (1) *     FROM Person.Address AS ad     WHERE l.Geo.STDistance(ad.SpatialLocation) < 20000     AND a2.AddressID IS NULL     ORDER BY l.Geo.STDistance(ad.SpatialLocation)     ) AS a3 JOIN Person.StateProvince AS s     ON s.StateProvinceID = COALESCE(a1.StateProvinceID,a2.StateProvinceID,a3.StateProvinceID) JOIN Person.CountryRegion AS c     ON c.CountryRegionCode = s.CountryRegionCode ; But this isn’t friendly-looking at all, and I’d use the method recommended by Isaac Kunen, who uses a table of numbers for the expanding circles. It feels old-school though, when I’m dealing with SQL 2012 (and later) versions. So why isn’t my query doing what it’s supposed to? Remember the query... WITH MyLocations AS (SELECT * FROM (VALUES ('LobsterPot Adelaide', geography::Point(-34.925806, 138.605073, 4326)),                        ('LobsterPot USA', geography::Point(42.524929, -87.858244, 4326))                ) t (Name, Geo)) SELECT l.Name, a.AddressLine1, a.City, s.Name AS [State], c.Name AS Country FROM MyLocations AS l CROSS APPLY (     SELECT TOP (1) *     FROM Person.Address AS ad     ORDER BY l.Geo.STDistance(ad.SpatialLocation)     ) AS a JOIN Person.StateProvince AS s     ON s.StateProvinceID = a.StateProvinceID JOIN Person.CountryRegion AS c     ON c.CountryRegionCode = s.CountryRegionCode ; Well, I just wasn’t reading http://msdn.microsoft.com/en-us/library/ff929109.aspx properly. The following requirements must be met for a Nearest Neighbor query to use a spatial index: A spatial index must be present on one of the spatial columns and the STDistance() method must use that column in the WHERE and ORDER BY clauses. The TOP clause cannot contain a PERCENT statement. The WHERE clause must contain a STDistance() method. If there are multiple predicates in the WHERE clause then the predicate containing STDistance() method must be connected by an AND conjunction to the other predicates. The STDistance() method cannot be in an optional part of the WHERE clause. The first expression in the ORDER BY clause must use the STDistance() method. Sort order for the first STDistance() expression in the ORDER BY clause must be ASC. All the rows for which STDistance returns NULL must be filtered out. Let’s start from the top. 1. Needs a spatial index on one of the columns that’s in the STDistance call. Yup, got the index. 2. No ‘PERCENT’. Yeah, I don’t have that. 3. The WHERE clause needs to use STDistance(). Ok, but I’m not filtering, so that should be fine. 4. Yeah, I don’t have multiple predicates. 5. The first expression in the ORDER BY is my distance, that’s fine. 6. Sort order is ASC, because otherwise we’d be starting with the ones that are furthest away, and that’s tricky. 7. All the rows for which STDistance returns NULL must be filtered out. But I don’t have any NULL values, so that shouldn’t affect me either. ...but something’s wrong. I do actually need to satisfy #3. And I do need to make sure #7 is being handled properly, because there are some situations (eg, differing SRIDs) where STDistance can return NULL. It says so at http://msdn.microsoft.com/en-us/library/bb933808.aspx – “STDistance() always returns null if the spatial reference IDs (SRIDs) of the geography instances do not match.” So if I simply make sure that I’m filtering out the rows that return NULL… …then it’s blindingly fast, I get the right results, and I’ve got the complex-but-brilliant plan that I wanted. It just wasn’t overly intuitive, despite being documented. @rob_farley

    Read the article

  • Rails destroy confirm with Jquery AJAX

    - by Mike
    I have got this working for the most part. My rails link is: <%= link_to(image_tag('/images/bin.png', :alt => 'Remove'), @business, :class => 'delete', :confirm => 'Are you sure?', :id => 'trash') %> :class = "delete" is calling an ajax function so that it is deleted and the page isn't refreshed that works great. But because the page doesn't refresh, it is still there. So my id trash is calling this jquery function: $('[id^=trash]').click(function(){ var row = $(this).closest("tr").get(0); $(row).hide(); return false; }); Which is hiding the row of whatever trash icon i clicked on. This also works great. I thought I had it all worked out and then I hit this problem. When you click on my trash can I have this confirm box pop up to ask you if you are sure. Regardless of whether you choose cancel or accept, the jquery fires and it hides the row. It isn't deleted, only hidden till you refresh the page. I tried changing it so that the prompt is done through jquery, but then rails was deleteing the row regardless of what i choose in my prompt because the .destroy function was being called when the prompt was being called. My question really is how can i get the value to cancel or accept from the rails confirm pop up so that in my jquery I can have an if statement that hides if they click accept and does nothing if they click cancel. EDIT: Answering Question below. That did not work. I tried changing my link to: <%= link_to(image_tag('/images/bin.png', :alt => 'Remove'), @business, :class => "delete", :onclick => "trash") %> and putting this in my jquery function trash(){ if(confirm("Are you sure?")){ var row = $(this).closest("tr").get(0); $(row).hide(); return false; } else { //they clicked no. } } But the function was never called. It just deletes it with no prompt and doesn't hide it. But that gave me an idea. I took the delete function that ajax was calling $('a.delete').click (function(){ $.post(this.href, {_method:'delete'}, null, "script"); $(row).hide(); }); And modified it implementing your code: remove :confirm = 'Are you sure?' $('a.delete').click (function(){ if(confirm("Are you sure?")){ var row = $(this).closest("tr").get(0); $.post(this.href, {_method:'delete'}, null, "script"); $(row).hide(); return false; } else { //they clicked no. return false; } }); Which does the trick.

    Read the article

  • Internet of Things Becoming Reality

    - by kristin.jellison
    The Internet of Things is not just on the radar—it’s becoming a reality. A globally connected continuum of devices and objects will unleash untold possibilities for businesses and the people they touch. But the “things” are only a small part of a much larger, integrated architecture. A great example of this comes from the healthcare industry. Imagine an expectant mother who needs to watch her blood pressure. She lives in a mountain village 100 miles away from medical attention. Luckily, she can use a small “wearable” device to monitor her status and wirelessly transmit the information to a healthcare hub in her village. Now, say the healthcare hub identifies that the expectant mother’s blood pressure is dangerously high. It sends a real-time alert to the patient’s wearable device, advising her to contact her doctor. It also pushes an alert with the patient’s historical data to the doctor’s tablet PC. He inserts a smart security card into the tablet to verify his identity. This ensures that only the right people have access to the patient’s data. Then, comparing the new data with the patient’s medical history, the doctor decides she needs urgent medical attention. GPS tracking devices on ambulances in the field identify and dispatch the closest one available. An alert also goes to the closest hospital with the necessary facilities. It sends real-time information on her condition directly from the ambulance. So when she arrives, they already have a treatment plan in place to ensure she gets the right care. The Internet of Things makes a huge difference for the patient. She receives personalized and responsive healthcare. But this technology also helps the businesses involved. The healthcare provider achieves a competitive advantage in its services. The hospital benefits from cost savings through more accurate treatment and better application of services. All of this, in turn, translates into savings on insurance claims. This is an ideal scenario for the Internet of Things—when all the devices integrate easily and when the relevant organizations have all the right systems in place. But in reality, that can be difficult to achieve. Core design principles are required to make the whole system work. Open standards allow these systems to talk to each other. Integrated security protects personal, financial, commercial and regulatory information. A reliable and highly available systems infrastructure is necessary to keep these systems running 24/7. If this system were just made up of separate components, it would be prohibitively complex and expensive for almost any organization. The solution is integration, and Oracle is leading the way. We’re developing converged solutions, not just from device to datacenter, but across devices, utilizing the Java platform, and through data acquisition and management, integration, analytics, security and decision-making. The Internet of Things (IoT) requires the predictable action and interaction of a potentially endless number of components. It’s in that convergence that the true value of the Internet of Things emerges. Partners who take the comprehensive view and choose to engage with the Internet of Things as a fully integrated platform stand to gain the most from the Internet of Things’ many opportunities. To discover what else Oracle is doing to connect the world, read about Oracle’s Internet of Things Platform. Learn how you can get involved as a partner by checking out the Oracle Java Knowledge Zone. Best regards, David Hicks

    Read the article

  • How to make a stack stable? Need help for an explicit resting contact scheme (2-dimensional)

    - by Register Sole
    Previously, I struggle with the sequential impulse-based method I developed. Thanks to jedediah referring me to this paper, I managed to rebuild the codes and implement the simultaneous impulse based method with Projected-Gauss-Seidel (PGS) iterative solver as described by Erin Catto (mentioned in the reference of the paper as [Catt05]). So here's how it currently is: The simulation handles 2-dimensional rotating convex polygons. Detection is using separating-axis test, with a SKIN, meaning closest points between two polygons is detected and determined if their distance is less than SKIN. To resolve collision, simultaneous impulse-based method is used. It is solved using iterative solver (PGS-solver) as in Erin Catto's paper. Error-correction is implemented using Baumgarte's stabilization (you can refer to either paper for this) using J V = beta/dt*overlap, J is the Jacobian for the constraints, V the matrix containing the velocities of the bodies, beta an error-correction parameter that is better be < 1, dt the time-step taken by the engine, and overlap, the overlap between the bodies (true overlap, so SKIN is ignored). However, it is still less stable than I expected :s I tried to stack hexagons (or squares, doesn't really matter), and even with only 4 to 5 of them, they would swing! Also note that I am not looking for a sleeping scheme. But I would settle if you have any explicit scheme to handle resting contacts. That said, I would be more than happy if you have a way of treating it generally (as continuous collision, instead of explicitly as a special state). Ideas I have tried: Using simultaneous position based error correction as described in the paper in section 5.3.2, turned out to be worse than the current scheme. If you want to know the parameters I used: Hexagons, side 50 (pixels) gravity 2400 (pixels/sec^2) time-step 1/60 (sec) beta 0.1 restitution 0 to 0.2 coeff. of friction 0.2 PGS iteration 10 initial separation 10 (pixels) mass 1 (unit is irrelevant for now, i modified velocity directly<-impulse method) inertia 1/1000 Thanks in advance! I really appreciate any help from you guys!! :) EDIT In response to Cholesky's comment about warm starting the solver and Baumgarte: Oh right, I forgot to mention! I do save the contact history and the impulse determined in this time step to be used as initial guess in the next time step. As for the Baumgarte, here's what actually happens in the code. Collision is detected when the bodies' closest distance is less than SKIN, meaning they are actually still separated. If at this moment, I used the PGS solver without Baumgarte, restitution of 0 alone would be able to stop the bodies, separated by a distance of ~SKIN, in mid-air! So this isn't right, I want to have the bodies touching each other. So I turn on the Baumgarte, where its role is actually to pull the bodies together! Weird I know, a scheme intended to push the body apart becomes useful for the reverse. Also, I found that if I increase the number of iteration to 100, stacks become much more stable, though the program becomes so slow. UPDATE Since the stack swings left and right, could it be something is wrong with my friction model? Current friction constraint: relative_tangential_velocity = 0

    Read the article

  • c# find nearest match to array of doubles

    - by Scott
    Given the code below, how do I compare a List of objects's values with a test value? I'm building a geolocation application. I'll be passing in longitude and latitude and would like to have the service answer back with the location closest to those values. I started down the path of converting to a string, and formatting the values down to two decimal places, but that seemed a bit too ghetto, and I'm looking for a more elegant solution. Any help would be great. Thanks, Scott public class Location : IEnumerable { public string label { get; set; } public double lat { get; set; } public double lon { get; set; } //Implement IEnumerable public IEnumerator GetEnumerator() { return (IEnumerator)this; } } [HandleError] public class HomeController : Controller { private List<Location> myList = new List<Location> { new Location { label="Atlanta Midtown", lon=33.657674, lat=-84.423130}, new Location { label="Atlanta Airport", lon=33.794151, lat=-84.387228}, new Location { label="Stamford, CT", lon=41.053758, lat=-73.530979}, ... } public static int Main(String[] args) { string inLat = "-80.987654"; double dblInLat = double.Parse(inLat); // here's where I would like to find the closest location to the inLat // once I figure out this, I'll implement the Longitude, and I'll be set }

    Read the article

  • Why jquery have problem with onbeforeprint even?

    - by Cesar Lopez
    Hi all, I have the following function. $(function() { $(".sectionHeader:gt(0)").click(function() { $(this).next(".fieldset").slideToggle("fast"); }); $("img[alt='minimize']").click(function(e) { $(this).closest("table").next(".fieldset").slideUp("fast"); e.stopPropagation(); return false; }); $("img[alt='maximize']").click(function(e) { $(this).closest("table").next(".fieldset").slideDown("fast"); e.stopPropagation(); return false; }); }); <script type="text/javascript"> window.onbeforeprint = expandAll; function expandAll(){ $(".fieldset:gt(0)").slideDown("fast"); } </script> For this html <table class="sectionHeader" ><tr ><td>Heading 1</td></tr></table> <div style="display:none;" class="fieldset">Content 1</div> <table class="sectionHeader" ><tr ><td>Heading 2</td></tr></table> <div style="display:none;" class="fieldset">Content 2</div> I have several div class="fieldset" over the page, but when I do print preview or print, I can see all divs sliding down before opening the print preview or printing but on the actual print preview or print out they are all collapse. I would appreciate if anyone comes with a solution for this. Anyone have any idea why is this or how to fix it? Thanks. PS:Using a does not work either ( I assume because jquery using toggle) and its not the kind of question I am looking for.

    Read the article

  • Ray-box Intersection Theory

    - by Myx
    Hello: I wish to determine the intersection point between a ray and a box. The box is defined by its min 3D coordinate and max 3D coordinate and the ray is defined by its origin and the direction to which it points. Currently, I am forming a plane for each face of the box and I'm intersecting the ray with the plane. If the ray intersects the plane, then I check whether or not the intersection point is actually on the surface of the box. If so, I check whether it is the closest intersection for this ray and I return the closest intersection. The way I check whether the plane-intersection point is on the box surface itself is through a function bool PointOnBoxFace(R3Point point, R3Point corner1, R3Point corner2) { double min_x = min(corner1.X(), corner2.X()); double max_x = max(corner1.X(), corner2.X()); double min_y = min(corner1.Y(), corner2.Y()); double max_y = max(corner1.Y(), corner2.Y()); double min_z = min(corner1.Z(), corner2.Z()); double max_z = max(corner1.Z(), corner2.Z()); if(point.X() >= min_x && point.X() <= max_x && point.Y() >= min_y && point.Y() <= max_y && point.Z() >= min_z && point.Z() <= max_z) return true; return false; } where corner1 is one corner of the rectangle for that box face and corner2 is the opposite corner. My implementation works most of the time but sometimes it gives me the wrong intersection. I was wondering if the way I'm checking whether the intersection point is on the box is correct or if I should use some other algorithm. Thanks.

    Read the article

  • Distance between Long Lat coord using SQLITE

    - by munchine
    I've got an sqlite db with long and lat of shops and I want to find out the closest 5 shops. So the following code works fine. if(sqlite3_prepare_v2(db, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { while (sqlite3_step(compiledStatement) == SQLITE_ROW) { NSString *branchStr = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)]; NSNumber *fLat = [NSNumber numberWithFloat:(float)sqlite3_column_double(compiledStatement, 1)]; NSNumber *fLong = [NSNumber numberWithFloat:(float)sqlite3_column_double(compiledStatement, 2)]; NSLog(@"Address %@, Lat = %@, Long = %@", branchStr, fLat, fLong); CLLocation *location1 = [[CLLocation alloc] initWithLatitude:currentLocation.coordinate.latitude longitude:currentLocation.coordinate.longitude]; CLLocation *location2 = [[CLLocation alloc] initWithLatitude:[fLat floatValue] longitude:[fLong floatValue]]; NSLog(@"Distance i meters: %f", [location1 getDistanceFrom:location2]); [location1 release]; [location2 release]; } } I know the distance from where I am to each shop. My question is. Is it better to put the distance back into the sqlite row, I have the row when I step thru the database. How do I do that? Do I use the UPDATE statement? Does someone have a piece of code to help me. I can read the sqlite into an array and then sort the array. Do you recommend this over the above approach? Is this more efficient? Finally, if someone has a better way to get the closest 5 shops, love to hear it.

    Read the article

  • (EXCEL)VBA Spin button which steps through in an sql databases date time

    - by Gulredy
    I have an sql Database table in MySQL which have lots of rows with varied date time values. For example: 2012-08-21 10:10:00 <-- with these date there are around 12 rows 2012-08-21 15:31:00 <-- with these date there are around 5 rows 2012-08-22 11:40:00 <-- with these date there are around 10 rows 2012-08-22 12:17:00 <-- with these date there are around 9 rows 2012-08-22 12:18:00 <-- with these date there are around 7 rows 2012-08-25 07:21:00 <-- with these date there are around 6 rows If the user clicks on the SpinButton1_SpinUp() or SpinButton1_SpinDown() button then it should do the following: The SpinButton1_SpinUp() button should filter out those data from an sql table which is the next after what we are currently on now. Example: We have currently selected: 2012-08-21 15:31:00. The user hits the SpinUp button then the program selects those date from the database, which is the next higher value like this one: 2012-08-22 11:40:00. So the user hits the SpinUp button the data which is selected in the database will change from those with date: 2012-08-21 15:31:00 to those with date: 2012-08-22 11:40:00 The SpinButton1_SpinDown() will do exactly the reverse of the SpinUp button. When the user hits the SpinDown button the data which is selected in the database will change from those with date: 2012-08-21 15:31:00 to those with date 2012-08-21 10:10:00 So I think the date which we are currently on, should be stored in a variable. But on button hit not every bigger or lower data should be selected in the database, only those which are the closest bigger or the closest lower date. How can I do this? I hope I described my problem understandable. My native language is not english, so misunderstandings can occur! Please ask if you don't understand something! Thank you for reading!

    Read the article

  • Click event on submit buttons only fires once

    - by Chris
    I subscribe to the click event on all submit buttons on my page once loaded. All buttons fire off the correct event when clicked, but this only works once. If you click any two buttons in a row the second button submits the form normally as opposed to running the script. What am I doing wrong?. Note: I load the form data from "myurl" using .load() then hook up to the submit buttons' click events in the complete event. $(document).ready(function() { //Load user content $("#passcontent").load("myurl", function() { //subscribe to click events for buttons to post the data back $('input[type=submit]').click(function() { return submitClick($(this)); }); }); }); function submitClick(submitButton) { submitButton.attr("disabled", true); alert(submitButton.closest("form").serialize()); $.post("myurl", submitButton.closest("form").serialize(), function(data) { alert("woop"); $("#passcontent").html(data); }); //Prevent normal form submission process from continuing return false; }

    Read the article

  • jquery validate not submitting after modal close bootstrap

    - by Mariana Hernandez
    I have a modal where i insert some data, but when i open the modal, close it, and the click the modal show button again, it doesnt submit of course because the validate is "acting" in the modal, but i closed it so its not showing... how can i prevent this? thanks it is similar to this jquery functions within modal only work on first open, after close and re-open they stop working but my functions are <script> $(document).ready(function() { $("#myModal").modal('show'); }); </script> and the validation one <script> $(document).ready(function(){ $('#form1').validate( { ignore: "", rules: { usu_login: { required: true }, usu_password: { required: true }, usu_email: { required: true }, usu_nombre1: { required: true }, usu_apellido1: { required: true }, usu_fecha_nac: { required: true }, usu_cedula: { required: true }, usu_telefono1: { required: true }, rol_id: { required: true }, dependencia_id: { required: true }, }, highlight: function(element) { $(element).closest('.grupo').addClass('has-error'); if($(".tab-content").find("div.tab-pane.active:has(div.has-error)").length == 0) { $(".tab-content").find("div.tab-pane:hidden:has(div.has-error)").each(function(index, tab) { var id = $(tab).attr("id"); $('a[href="#' + id + '"]').tab('show'); }); } }, unhighlight: function(element) { $(element).closest('.grupo').removeClass('has-error'); } }); }); </script> So i dont know how to apply the answer of the above =(

    Read the article

  • jQuery pagination without all the rows of data before hand

    - by Aaron Mc Adam
    Hi guys, I'm trying to find a solution for paginating my search results. I have a built the links and everything works without jQuery. I've also got AJAX working for the links, but I just need a way of tidying up the list of links, as some search results return up to 60 pages and the links spread to two rows in my template. I am searching the Amazon API, and can only return 10 results at a time. Upon clicking the pagination links, the next 10 results are returned. I have access to the total results number from the XML, but not all the data at once, so I can't put all the data into a "hiddenResults" div that the jQuery Pagination plugin needs. Here is the jQuery I have for the pagination: var $pagination = $("#pagination ul"); $pagination.delegate('.pagenumbers', 'click', function() { var $$this = $(this); $$this.closest('li').addClass('cached'); $pagination.find("#currentPage").removeAttr('id').wrapInner($('<a>', {'class':'pagenumbers', 'href':'book_data.php?keywords='+keywords})); $$this.closest('li').attr('id','currentPage').html( $$this.text() ); $.ajax({ type : "GET", cache : false, url : "book_data.php", data : { keywords : keywords, page : $$this.text() }, success : show_results }); return false; }); function show_results(res) { $("#searchResults").replaceWith($(res).find('#searchResults')).find('table.sortable tbody tr:odd').addClass('odd'); detailPage(); selectForm(); if ( ! ( $pagination.find('li').hasClass('cached') ) ) { $.get("book_data.php", { keywords : keywords, page : ( $pagination.find("#currentPage").text() + 1 ) } ); } }

    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

  • Algorithm to pick values from set to match target value?

    - by CSharperWithJava
    I have a fixed array of constant integer values about 300 items long (Set A). The goal of the algorithm is to pick two numbers (X and Y) from this array that fit several criteria based on input R. Formal requirement: Pick values X and Y from set A such that the expression X*Y/(X+Y) is as close as possible to R. That's all there is to it. I need a simple algorithm that will do that. Additional info: The Set A can be ordered or stored in any way, it will be hard coded eventually. Also, with a little bit of math, it can be shown that the best Y for a given X is the closest value in Set A to the expression X*R/(X-R). Also, X and Y will always be greater than R From this, I get a simple iterative algorithm that works ok: int minX = 100000000; int minY = 100000000; foreach X in A if(X<=R) continue; else Y=X*R/(X-R) Y=FindNearestIn(A, Y);//do search to find closest useable Y value in A if( X*Y/(X+Y) < minX*minY/(minX+minY) ) then minX = X; minY = Y; end end end I'm looking for a slightly more elegant approach than this brute force method. Suggestions?

    Read the article

  • Why jquery have problem with onbeforeprint event?

    - by Cesar Lopez
    Hi all, I have the following function. $(function() { $(".sectionHeader:gt(0)").click(function() { $(this).next(".fieldset").slideToggle("fast"); }); $("img[alt='minimize']").click(function(e) { $(this).closest("table").next(".fieldset").slideUp("fast"); e.stopPropagation(); return false; }); $("img[alt='maximize']").click(function(e) { $(this).closest("table").next(".fieldset").slideDown("fast"); e.stopPropagation(); return false; }); }); <script type="text/javascript"> window.onbeforeprint = expandAll; function expandAll(){ $(".fieldset:gt(0)").slideDown("fast"); } </script> For this html <table class="sectionHeader" ><tr ><td>Heading 1</td></tr></table> <div style="display:none;" class="fieldset">Content 1</div> <table class="sectionHeader" ><tr ><td>Heading 2</td></tr></table> <div style="display:none;" class="fieldset">Content 2</div> I have several div class="fieldset" over the page, but when I do print preview or print, I can see all divs sliding down before opening the print preview or printing but on the actual print preview or print out they are all collapse. I would appreciate if anyone comes with a solution for this. Anyone have any idea why is this or how to fix it? Thanks. PS:Using a does not work either ( I assume because jquery using toggle) and its not the kind of question I am looking for.

    Read the article

  • What is the optimum way to select the most dissimilar individuals from a population?

    - by Aaron D
    I have tried to use k-means clustering to select the most diverse markers in my population, for example, if we want to select 100 lines I cluster the whole population to 100 clusters then select the closest marker to the centroid from each cluster. The problem with my solution is it takes too much time (probably my function needs optimization), especially when the number of markers exceeds 100000. So, I will appreciate it so much if anyone can show me a new way to select markers that maximize diversity in my population and/or help me optimize my function to make it work faster. Thank you # example: library(BLR) data(wheat) dim(X) mdf<-mostdiff(t(X), 100,1,nstart=1000) Here is the mostdiff function that i used: mostdiff <- function(markers, nClust, nMrkPerClust, nstart=1000) { transposedMarkers <- as.array(markers) mrkClust <- kmeans(transposedMarkers, nClust, nstart=nstart) save(mrkClust, file="markerCluster.Rdata") # within clusters, pick the markers that are closest to the cluster centroid # turn the vector of which markers belong to which clusters into a list nClust long # each element of the list is a vector of the markers in that cluster clustersToList <- function(nClust, clusters) { vecOfCluster <- function(whichClust, clusters) { return(which(whichClust == clusters)) } return(apply(as.array(1:nClust), 1, vecOfCluster, clusters)) } pickCloseToCenter <- function(vecOfCluster, whichClust, transposedMarkers, centers, pickHowMany) { clustSize <- length(vecOfCluster) # if there are fewer than three markers, the center is equally distant from all so don't bother if (clustSize < 3) return(vecOfCluster[1:min(pickHowMany, clustSize)]) # figure out the distance (squared) between each marker in the cluster and the cluster center distToCenter <- function(marker, center){ diff <- center - marker return(sum(diff*diff)) } dists <- apply(transposedMarkers[vecOfCluster,], 1, distToCenter, center=centers[whichClust,]) return(vecOfCluster[order(dists)[1:min(pickHowMany, clustSize)]]) } }

    Read the article

  • find nearest match to array of doubles

    - by Scott
    Given the code below, how do I compare a List of objects's values with a test value? I'm building a geolocation application. I'll be passing in longitude and latitude and would like to have the service answer back with the location closest to those values. I started down the path of converting to a string, and formatting the values down to two decimal places, but that seemed a bit too ghetto, and I'm looking for a more elegant solution. public class Location : IEnumerable { public string label { get; set; } public double lat { get; set; } public double lon { get; set; } //Implement IEnumerable public IEnumerator GetEnumerator() { return (IEnumerator)this; } } [HandleError] public class HomeController : Controller { private List<Location> myList = new List<Location> { new Location { label="Atlanta Midtown", lon=33.657674, lat=-84.423130}, new Location { label="Atlanta Airport", lon=33.794151, lat=-84.387228}, new Location { label="Stamford, CT", lon=41.053758, lat=-73.530979}, ... } public static int Main(String[] args) { string inLat = "-80.987654"; double dblInLat = double.Parse(inLat); // here's where I would like to find the closest location to the inLat // once I figure out this, I'll implement the Longitude, and I'll be set }

    Read the article

  • using Jquery, replace html elements with own values

    - by loviji
    Hello, I have a table, has many rows. for example one of from rows(all rows are same): <tr> <td> <input type="text" /> </td> <td> <textarea cols="40" rows="3" ></textarea> </td> <td> <select> //options </select> </td> <td> <input type="text" /> </td> <td> <input type="checkbox" /> </td> </tr> Rows can be dynamically added by jquery after button click. I'm trying to do: after button click add new row(I do it) and replace previous row Html Elements(input type=text, textarea, select, input type=text, /[input type="checkbox" must be safe]) with its own values. And after if i click on row(anyrow), i want to rollback previous operation. i.e. replace texts with html element. and htmlElement.val()=text. Added after 30 minutes: I wrote for input type=text element and textarea element this. $("#btnAdd").click(function() { $input = $('#mainTable tbody>tr:last').closest("tr").find("td > input:text"); $input.replaceWith($input.val()); $textArea = $('#mainTable tbody>tr:last').closest("tr").find("td > textarea"); $textArea.replaceWith($textArea.val()); }); is this a good idea?

    Read the article

  • jQuery: Preventing an event from being attached more than once?

    - by Evan Carroll
    Essentially, I have an element FOO that I want when clicked to attach a click event to a completely separate set of elements BAR, so that when they're clicked they can revert FOO to its previous content. I only want this event attached once. When FOO is clicked, its content is cached away in $back_up, and a trigger is added on the BAR set so that when clicked they can revert FOO back to its previous state. Is there a clever way to do this? Like to only .bind() if the event doesn't already exist? $('<div class="noprint little check" />').click( function () { var $warranty_explaination = $(this).closest('.page').children('.warranty_explaination'); var $back_up = $warranty_explaination.clone(true); $(this).closest('.page').find('.warranties .check:not(.noprint)').click( function () { /* This is the code I don't want to fire more than once */ /*, I just want it to be set to whatever is in the $back_up */ alert('reset'); $warranty_explaination.replaceWith( $back_up ) } ); $warranty_explaination.html('asdf') } ) Currently, the best way I can think to do this is to attach a class, and select where that class doesn't exist.

    Read the article

  • jQuery && Google Chrome

    - by Happy
    This script works perfectly in all the browsers, except Google Chrome. $(document).ready(function(){ $(".banners-anim img").each(function(){ var hover_width = $(this).width(); var hover_height = $(this).height(); var unhover_width = (hover_width - 30); $(this).width(unhover_width); var unhover_height = $(this).height(); $(this).closest("li").height(unhover_height); var offset = "-" + ((hover_height - unhover_height)/2) + "px"; $(this).closest("span").css({'position':'absolute', 'left':'0', 'top':'25px', 'width':'100%'}); $(this).hover(function(){ $(this).animate({width: hover_width, marginTop: offset}, "fast") },function(){ $(this).animate({width: unhover_width, marginTop: 0}, "fast") }); }); }); Chrome doesn't recognize changed image attributes. When width of the img changes, height also changes. Even not in Chrome.. $(this).width(unhover_width); var unhover_height = $(this).height(); unhover_height gives 0. Full code of this script (html included) - unhover_height Please help to fix this. Thanks.

    Read the article

  • Why my jquery function is not firing on Firefox

    - by Cristian Boariu
    I have some trouble with some jquery method (for some checkboxes I want them to fire on checked/unchecked so I can do something then). This method works perfectly on Chrome and IE but not on latest FF. jQuery(function () { jQuery(':checkbox').change(function () { var counter = jQuery('.count').text(); var thisCheck = jQuery(this); if (thisCheck.is(':checked')) { counter++; //apply green color to the selected row jQuery(this).closest('tr').addClass('checked'); } else { counter--; //remove green color to the selected row jQuery(this).closest('tr').removeClass('checked'); } jQuery('.count').html(counter); //enable export button when there are selected emails to be exported if (counter > 0) { jQuery(".exportButton").removeAttr("disabled", ""); } else { jQuery(".exportButton").attr("disabled", "disabled"); } }); }); Basically it's simply not firing...Even with Debug is not catching the first line (function declare nor other lines too). If I move this javascript(without function declare) inside jQuery(document).ready(function ($) { all works nice on Firefox too... Yes, I do use jQuery.noConflict(); before jQuery(document).ready(function ($) { Do you know why this happens?

    Read the article

  • jquery - DOM traversal question

    - by David
    Hi, Basically what I have here is a button that adds a new list item to an unordered list. Within this list item is a dropdown box (.formSelector) that when changed triggers an ajax call to get the values for another dropdown box (.fieldSelector) in the same list item. The problem is on this line: $(this).closest(".fieldSelector").append( If I change it to $(".fieldSelector").append( the second box updates correctly. The problem with this is that when I have multiple list items it updates every dropdown box on the page with the class fieldSelector, which is undesirable. How can I traverse the DOM to just pick the fieldSelector in the current list item? Any help is greatly appreciated. Complete code: $("button", "#newReportElement").click(function() { $("#reportElements").append("<li class=\"ui-state-default\"> <span class=\"test ui-icon ui-icon-arrowthick-2-n-s \"></span><span class=\"ui-icon ui-icon-trash deleteRange \"></span> <select name=\"form[]\" class=\"formSelector\"><? foreach ($forms->result() as $row) { echo "<option value='$row->formId'>$row->name</option>"; }?></select><select class=\"fieldSelector\" name=\"field[]\"></select></li>"); $(".deleteRange").button(); $('.formSelector').change(function() { var id = $(this).val(); var url = "<? echo site_url("report/formfields");?>" + "/" + id; var atext = "ids:"; $.getJSON(url, function(data){ $.each(data.items, function(i,item){ $(this).closest(".fieldSelector").append( $('<option></option>').val(item.formId).html(item.formLabel) ); }); }); }); return false; });

    Read the article

  • Issue pushing object into an array JS

    - by Javacadabra
    I'm having an issue placing an object into my array in javascript. This is the code: $('.confirmBtn').click(function(){ //Get reference to the Value in the Text area var comment = $("#comments").val(); //Create Object var orderComment = { 'comment' : comment }; //Add Object to the Array productArray.push(orderComment); //update cookie $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' }); }); However when I print the array this is the output: Array ( [0] => Array ( [stockCode] => CBL202659/A [quantity] => 8 ) [1] => Array ( [stockCode] => CBL201764 [quantity] => 6 ) [2] => TEST TEST ) I would like it to look like this: Array ( [0] => Array ( [stockCode] => CBL202659/A [quantity] => 8 ) [1] => Array ( [stockCode] => CBL201764 [quantity] => 6 ) [2] Array( [comment] => TEST TEST ) I added products to the array in a similar way and it worked fine: var productArray = []; // Will hold order Items $(".orderBtn").click(function(event){ //Check to ensure quantity > 0 if(quantity == 0){ console.log("Quantity must be greater than 0") }else{//It is so continue //Show the order Box $(".order-alert").show(); event.preventDefault(); //Get reference to the product clicked var stockCode = $(this).closest('li').find('.stock_code').html(); //Get reference to the quantity selected var quantity = $(this).closest('li').find('.order_amount').val(); //Order Item (contains stockCode and Quantity) - Can add whatever data I like here var orderItem = { 'stockCode' : stockCode, 'quantity' : quantity }; //Check if cookie exists if($.cookie('order_cookie') === undefined){ console.log("Creating new cookie"); //Add object to the Array productArray.push(orderItem);

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >