Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

stoops posted:

64799 358.500 89.500 800.325 271.256 66.543
64800 359.500 89.500 800.370 271.257 66.551


Does one pixel position equal one line of text, or is it possible that it has more? How do the two columns correspond to the x/y coordinates of the image?

Adbot
ADBOT LOVES YOU

stoops
Jun 11, 2001

obstipator posted:


Do the 2nd and 3rd rows always follow the pattern of +1 for the 2nd until it hits360, then loops back to 0 and increments the 3rd row by 1?

Yes it does. Awesome thanks, I'll try that.



KARMA! posted:

Does one pixel position equal one line of text, or is it possible that it has more? How do the two columns correspond to the x/y coordinates of the image?

Yes, one pixel position equals only one line of text. The x/y i'm passing are the lon(second column) and lat(3rd column)

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

stoops posted:

I have a textfile with lines like this: (about 65000 lines, 6 columns)

1 0.500 -89.500 725.330 88.743 -66.551
2 1.500 -89.500 725.359 88.744 -66.543
...

64799 358.500 89.500 800.325 271.256 66.543
64800 359.500 89.500 800.370 271.257 66.551


What I need to do is read that text file and then do a search for the line that closely matches the numbers in the 2nd and 3rd columns.
I don't know much javascript, so apologies for that. (I did this in php with a preg_split. Is there something like that in javascript?)

Is it faster if I put each line in an array like this and then search thru those arrays?

arrayLine 0 (1, 0.500, -89.500, 725.330, 88.743, -66.551)
arrayLine 1 (2, 1.500, -89.500, 725.359, 88.744, -66.543)

Currently, all I have is the reading of the text file into a variable. Any point in the right direction would help.

JavaScript code:
var split_lines = original_text.split('\n').map(
	function(line) {
		return line.split(' ').map(Number);
	})
split_lines is then a 2-dimensional array of numbers.

I.e. the first line is split_lines[0]. The second column of the first line is split_lines[0][1].

Wheany fucked around with this message at 23:01 on May 9, 2014

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Okay and I only now realized that I didn't really answer your question.

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

stoops posted:

Yes it does. Awesome thanks, I'll try that.


Yes, one pixel position equals only one line of text. The x/y i'm passing are the lon(second column) and lat(3rd column)


JavaScript code:
data = "1 0.500 -89.500 725.330 88.743 -66.551
2 1.500 -89.500 725.359 88.744 -66.543
64799 358.500 89.500 800.325 271.256 66.543
64800 359.500 89.500 800.370 271.257 66.551";


var coords = [];
var data_array = data.split('\n').map(
    function(line) {
        line_array = line.split(' ');
        var lon = line_array[1];
        var lat = line_array[2];
        if (coords[lon] == undefined) coords[lon] = [];
        coords[lon][lat] = line;
    });
At this point you'll have a coords array that you could use to pull out the right line, instead of making a request to an php script. I'd rather put the x/y mouse positions in the coords array instead of the lat/lon, but I don't the conversion on that.

Any questions?

Dominoes
Sep 20, 2007

Having trouble returning something from an inline function. I'm following this guide on pulling elevation data from Google maps via APIv3. The example doesn't return anything. I'd like to, but can't using the inline function example. I can print the correct data, but not return it.

If I try to make it a non-inline function, 'results' can't be found. I read on Stack overflow to add an extra () after the inline function to make it work, but get 'uncaught typerror: undefined is not a function' when I try.

JavaScript code:
function getElevation(event) {
    var locations = []
    locations.push(event.latLng)
    var positionalRequest = {
        'locations': locations
    }
    return elevator.getElevationForLocations(positionalRequest, function(results, status) {
        if (status == google.maps.ElevationStatus.OK) {
            if (results[0]) {
                elevation = results[0].elevation
            }
        }
         return elevation
    })
}

Dominoes fucked around with this message at 14:10 on May 11, 2014

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Dominoes posted:

Having trouble returning something from an inline function. I'm following this guide on pulling elevation data from Google maps via APIv3. The example doesn't return anything. I'd like to, but can't using the inline function example. I can print the correct data, but not return it.

If I try to make it a non-inline function, 'results' can't be found. I read on Stack overflow to add an extra () after the inline function to make it work, but get 'uncaught typerror: undefined is not a function' when I try.

JavaScript code:
function getElevation(event) {
    var locations = []
    locations.push(event.latLng)
    var positionalRequest = {
        'locations': locations
    }
    return elevator.getElevationForLocations(positionalRequest, function(results, status) {
        if (status == google.maps.ElevationStatus.OK) {
            if (results[0]) {
                elevation = results[0].elevation
            }
         return elevation
    })
}
You have some weird bracing in your code. The "if (status ==" line's opening curly brace is closed after the "return elevation" row, but you never close the function(results, status) opening brace.

Dominoes
Sep 20, 2007

Wheany posted:

You have some weird bracing in your code. The "if (status ==" line's opening curly brace is closed after the "return elevation" row, but you never close the function(results, status) opening brace.
Copy/paste error. Edited in the missing brace. Doesn't affect nature of problem.

Looking at the examples I read that included the extra (), they had the return/variable assignment directly before 'function', which may be why that fix doesn't work. I can't do that here, since there's a bit of google code that needs to go there instead.

I feel like there should just be a method to google latLng instances, so you could just do location.elevation(). Instead it's a mess.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Well, if I reformat your code like this:


JavaScript code:
function getElevation(event) {
    var positionalRequest = {
        'locations': [event.latLng]
    }
	var callback = function(results, status) {
		var cb_elevation;
        if (status == google.maps.ElevationStatus.OK) {
            if (results[0]) {
                cb_elevation = results[0].elevation;
            }
        }
         return cb_elevation;
    }
	
    var elevation = elevator.getElevationForLocations(positionalRequest, callback);
	
	return elevation;
}
You can add a breakpoint on the "return elevation" line to inspect its value.

I noticed that the original "elevation" in your code was a global variable and that its value is either whatever its value was before (or undefined if it has been never set before) or the value of results[0].elevation, if status == google.maps.ElevationStatus.OK

I renamed that variable to cb_elevation and made it local to the inner function and added a new local elevation variable to the outer function.

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

Dominoes posted:

Having trouble returning something from an inline function. I'm following this guide on pulling elevation data from Google maps via APIv3. The example doesn't return anything. I'd like to, but can't using the inline function example. I can print the correct data, but not return it.

If I try to make it a non-inline function, 'results' can't be found. I read on Stack overflow to add an extra () after the inline function to make it work, but get 'uncaught typerror: undefined is not a function' when I try.

JavaScript code:
function getElevation(event) {
    var locations = []
    locations.push(event.latLng)
    var positionalRequest = {
        'locations': locations
    }
    return elevator.getElevationForLocations(positionalRequest, function(results, status) {
        if (status == google.maps.ElevationStatus.OK) {
            if (results[0]) {
                elevation = results[0].elevation
            }
        }
         return elevation
    })
}

Wait, is "elevation" what you want to return from getElevation? If so I think you're confused at a few levels here.

The function you pass to getElevationForLocations, is, as far as I can tell, supposed to be a callback function. That means the request is sent off, and when the answer is found your callback is called. The point here is that the result is asynchronous, you can't just get the answer back and return it from your function getElevation.

Secondly, even if that were not the case, what you're trying to do doesn't make any sense. getElevationForLocations is a function that takes a function. Why do you think that, by returning "elevation" in the passed function, getElevationForLocations will itself return "elevation"? There's no reason for that to happen. getElevationForLocations like returns either nothing or some sort of status, and that is what you're returning from getElevation

Edit: Read this

quote:

Accessing the Elevation service is asynchronous, since the Google Maps API needs to make a call to an external server. For that reason, you need to pass a callback method to execute upon completion of the request. This callback method should process the result(s). Note that the Elevation service returns a status code (ElevationStatus) and an array of separate ElevationResult objects.

HappyHippo fucked around with this message at 16:10 on May 11, 2014

Dominoes
Sep 20, 2007

Wheany posted:

Well, if I reformat your code like this:

JavaScript code:
function getElevation(event) {
    var positionalRequest = {
        'locations': [event.latLng]
    }
	var callback = function(results, status) {
		var cb_elevation;
        if (status == google.maps.ElevationStatus.OK) {
            if (results[0]) {
                cb_elevation = results[0].elevation;
            }
        }
         return cb_elevation;
    }
	
    var elevation = elevator.getElevationForLocations(positionalRequest, callback);
	
	return elevation;
}
You can add a breakpoint on the "return elevation" line to inspect its value.

I noticed that the original "elevation" in your code was a global variable and that its value is either whatever its value was before (or undefined if it has been never set before) or the value of results[0].elevation, if status == google.maps.ElevationStatus.OK

I renamed that variable to cb_elevation and made it local to the inner function and added a new local elevation variable to the outer function.
Thank you. I tried setting that, but it looks like it has the same issue; I can pull the elevation data and set it to a variable in the callback function, print it, do something with it immediately etc, but not pass it to the rest of my program.

HappyHippo posted:

Wait, is "elevation" what you want to return from getElevation? If so I think you're confused at a few levels here.

The function you pass to getElevationForLocations, is, as far as I can tell, supposed to be a callback function. That means the request is sent off, and when the answer is found your callback is called. The point here is that the result is asynchronous, you can't just get the answer back and return it from your function getElevation.

Secondly, even if that were not the case, what you're trying to do doesn't make any sense. getElevationForLocations is a function that takes a function. Why do you think that, by returning "elevation" in the passed function, getElevationForLocations will itself return "elevation"? There's no reason for that to happen. getElevationForLocations like returns either nothing or some sort of status, and that is what you're returning from getElevation

Edit: Read this
Hey, I think you found the origin of the problem. Ie the elevation is returned when it's ready, not instantly. I have a working, but messy solution: Wedge the rest of my relevant code into the callback function instead of trying to split into multiple clean, reusable functions.

Dominoes fucked around with this message at 17:13 on May 11, 2014

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Dominoes posted:

I have a working, but messy solution: Wedge the rest of my relevant code into the callback function instead of trying to split into multiple clean, reusable functions.

Why can't you call those reusable functions from your callback?

(Google's docs are somewhat unhelpful in saying "Elevation service returns a status code (ElevationStatus) and an array of separate ElevationResult objects", when it's really not a return value. It makes sense once you're used to the async callback pattern, but I think would be better as "Elevation service invokes the callback with a status code …".)

Dominoes
Sep 20, 2007

Subjunctive posted:

Why can't you call those reusable functions from your callback?

(Google's docs are somewhat unhelpful in saying "Elevation service returns a status code (ElevationStatus) and an array of separate ElevationResult objects", when it's really not a return value. It makes sense once you're used to the async callback pattern, but I think would be better as "Elevation service invokes the callback with a status code …".)
Guess I could!

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dominoes posted:

Guess I could!

I know you post in the Python thread a lot, so I'll point this out: JS is similar to Python in a lot of ways and you can write a lot of stuff in pretty much the same way, but you'll really need to wrap your head around the idea that a lot of stuff you'll be doing with JS is asynchronous. Callbacks are a way of life.

Dominoes
Sep 20, 2007

Thermopyle posted:

I know you post in the Python thread a lot, so I'll point this out: JS is similar to Python in a lot of ways and you can write a lot of stuff in pretty much the same way, but you'll really need to wrap your head around the idea that a lot of stuff you'll be doing with JS is asynchronous. Callbacks are a way of life.
A lot of what I've done on this project is adapting existing python code, so users can manipulate Gmaps live instead of having to go back to the django page and resubmit. It's been a smooth transition so far. There's been a bit of rewriting shortcuts the long way while I figure out equivalent ones in js. I'm taking a few things I like from Python that are optional, but nonstandard, like == instead of === and no semicolons.


Speaking of which: Is exception handling in JS used only for problems? I got this impression after reading several pages describing how empty catch statements are never a good idea. Here's an example. The assumption seems to be that try/catch is only used when something goes wrong, and isn't used for expected behaviors. 'Easier to ask for forgiveness than permission' and duck-typing in Python are used all the time. Is this just an issue of different philosophies driving the guidelines I've read?

Dominoes fucked around with this message at 22:56 on May 13, 2014

stoops
Jun 11, 2001

KARMA! posted:

JavaScript code:
data = "1 0.500 -89.500 725.330 88.743 -66.551
2 1.500 -89.500 725.359 88.744 -66.543
64799 358.500 89.500 800.325 271.256 66.543
64800 359.500 89.500 800.370 271.257 66.551";


var coords = [];
var data_array = data.split('\n').map(
    function(line) {
        line_array = line.split(' ');
        var lon = line_array[1];
        var lat = line_array[2];
        if (coords[lon] == undefined) coords[lon] = [];
        coords[lon][lat] = line;
    });
At this point you'll have a coords array that you could use to pull out the right line, instead of making a request to an php script. I'd rather put the x/y mouse positions in the coords array instead of the lat/lon, but I don't the conversion on that.

Any questions?


Thanks (and you too, obstipator).

I ended up using this, but now my textfile data has changed, and I'm not sure how to go about it.

Before, my textfile would be like this:

code:
        1      0.500    -89.500    712.256     88.743    -66.551
        2      1.500    -89.500    712.286     88.744    -66.543
        3      2.500    -89.500    712.316     88.745    -66.534
        4      3.500    -89.500    712.346     88.747    -66.525
But now, there is "Information" at the top of the file:

code:
 zn0=0.12000 cm-3 temp=12000.000 deg k  v=20.000 km/sec
   asymn= 0.000 asyms= 0.000; switch=0 where 0=harmonic lifetime in lat., 1=old Ulysses, 2=new Uly
         
sector #      elon      elat     theory       ra        dec
        1      0.500    -89.500    712.256     88.743    -66.551
        2      1.500    -89.500    712.286     88.744    -66.543
        3      2.500    -89.500    712.316     88.745    -66.534
        4      3.500    -89.500    712.346     88.747    -66.525
        5      4.500    -89.500    712.376     88.749    -66.516
        6      5.500    -89.500    712.406     88.751    -66.508
i want to start reading my data right at

1 0.500 -89.500 712.256 88.743 -66.551

I tried to do a, data.split ("sector # elon elat theory ra dec"),

but that gives me an extra line at the very top before my real data begins, so it reads like this:

code:
	(extra line is here)
        1      0.500    -89.500    712.256     88.743    -66.551
        2      1.500    -89.500    712.286     88.744    -66.543
        3      2.500    -89.500    712.316     88.745    -66.534
        4      3.500    -89.500    712.346     88.747    -66.525
        5      4.500    -89.500    712.376     88.749    -66.516
        6      5.500    -89.500    712.406     88.751    -66.508
Any way to make my data start without the extra line? Thanks for the help.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



stoops posted:

Any way to make my data start without the extra line? Thanks for the help.

You could just slice() the split array:
code:
var data_array = data.split('\n').slice(1).map(//etc
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

You might want to check your first row to make sure it's not header data before you slice it up, but I'm not sure if that's going to be a problem based on what you posted.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Could put a newline in the split string, then it would be consumed.

Vicar
Oct 20, 2007

Dominoes posted:

A lot of what I've done on this project is adapting existing python code, so users can manipulate Gmaps live instead of having to go back to the django page and resubmit. It's been a smooth transition so far. There's been a bit of rewriting shortcuts the long way while I figure out equivalent ones in js. I'm taking a few things I like from Python that are optional, but nonstandard, like == instead of === and no semicolons.
I'd stick to using === in JS if you're new to it, it has some type coercion rules that can take some getting used to (check out http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/).

As for semicolons, I'd also strongly recommend just using them. If you really don't like them, you should (must) prefix lines starting with ([ with semicolons, which in my opinion looks worse.

Dominoes posted:

Speaking of which: Is exception handling in JS used only for problems? I got this impression after reading several pages describing how empty catch statements are never a good idea. Here's an example. The assumption seems to be that try/catch is only used when something goes wrong, and isn't used for expected behaviors. 'Easier to ask for forgiveness than permission' and duck-typing in Python are used all the time. Is this just an issue of different philosophies driving the guidelines I've read?

I'd say Javascript is more in the look before you leap land.

DholmbladRU
May 4, 2006
On a web application accessed from ipad safari I am using the jQuery to perform autocomplete. The autocomplete is working however I am unable to scroll through the items. I have attempted to accomplish this via CSS however it does not seem to work. I would like to use javascript to add scroll to the autocomplete, however it seems to not work.

Was attempting to use something similar to below to add scroll, but was unsuccessful.

code:
      document.getElementById(id).addEventListener("touchstart", function(event) {
                    scrollStartPos=this.scrollTop+event.touches[0].pageY;
                    event.preventDefault();
                  
                },false);
                document.getElementById(id).addEventListener("touchmove", function(event) {
                    this.scrollTop=scrollStartPos-event.touches[0].pageY;
                    event.preventDefault();
    
                },false);

Dominoes
Sep 20, 2007

Looking for advice on regex in Javascript. I have several different regegexes, and I've been trying to filter the valid one(s) by checking if the result exists. However, Even the invalid ones return a valid array: Just with undefined values on the parts that don't match.

ie:


JavaScript code:
 
var degMinLat = /([NSns])\s*(\d{2})(?:-|\s*)((\d{2})(\.(\d+))|\d{2}(\s|$))?/.exec(lat)
var degMinLon = /([EWew])\s*(\d{3})(?:-|\s*)((\d{2})(\.(\d+))|\d{2}(\s|$))?/.exec(lon)

var degMinLat2 = /([NSns])\s*(\d{1,2})(?:-|\s+)((\d{2})(\.(\d+))|\d{2}(\s|$))?/.exec(lat)
var degMinLon2 = /([EWew])\s*(\d{1,3})(?:-|\s+)((\d{2})(\.(\d+))|\d{2}(\s|$))?/.exec(lon)

etc
I've been checking validity with statements like:

JavaScript code:
if (! degMinLat){}
, and biting off an an arbitrary one that passes. However, even the ones that don't pass pass some matching groups, with others left as undefined. This quietly gives bogus results, and makes testing if a string passes the entire regex a pain. Any suggestions? I suppose I could do some iterating over results and failed flags, but there's got to be a cleaner way

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Dominoes posted:

JavaScript code:
 
var degMinLat = /([NSns])\s*(\d{2})(?:-|\s*)((\d{2})(\.(\d+))|\d{2}(\s|$))?/.exec(lat)
var degMinLon = /([EWew])\s*(\d{3})(?:-|\s*)((\d{2})(\.(\d+))|\d{2}(\s|$))?/.exec(lon)

var degMinLat2 = /([NSns])\s*(\d{1,2})(?:-|\s+)((\d{2})(\.(\d+))|\d{2}(\s|$))?/.exec(lat)
var degMinLon2 = /([EWew])\s*(\d{1,3})(?:-|\s+)((\d{2})(\.(\d+))|\d{2}(\s|$))?/.exec(lon)

etc

What are you matching against?

Dominoes
Sep 20, 2007

Wheany posted:

What are you matching against?
User-input of lat/lon coordinates in various formats.

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
When you RegExp your strings, is it expected that your coordinates will always return non-undefined values for the regex matches, or is it OK for the number of "undefined" returns values to fluctuate?
For instance, if you jam in "N32.1234" you might get [32, 1234, undefined] but if I jam in "N32" I get [32, undefined, undefined]. Is the second example still a valid lat/lng?

I can't offer you anything native to make your life easier, but LoDash has a few functions you can use.

code:
// Returns the count of "undefined" in an array
var countUndefined = function(data) { 
    return _.filter(data, function(item) { 
        return item === undefined; 
    }).length;
}

// Regex
var degMinLat = /([NSns])\s*(\d{2})(?:-|\s*)((\d{2})(\.(\d+))|\d{2}(\s|$))?/.exec(lat);

// Validation
if (countUndefined(degMinLat) > 2) {
    alert('Nope');
}
I've only skimmed the docs so maybe someone knows something better.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Dominoes posted:

User-input of lat/lon coordinates in various formats.

Ok, please post some valid examples, and possibly some invalid examples.

It's impossible to go backwards from the posted regexes, because they might have some errors. Also because regexes are a write-only language.

For experimenting, I have used The Regex Coach http://www.weitz.de/regex-coach/

Blinkz0rz
May 27, 2001

MY CONTEMPT FOR MY OWN EMPLOYEES IS ONLY MATCHED BY MY LOVE FOR TOM BRADY'S SWEATY MAGA BALLS
If you're accepting user input for lat/longs you might want to rethink your system.

Is your audience technical enough that they have to input exact coordinates?

If not, maybe you should geocode addresses and not worry about regexing coordinates.

If so, you might want to reverse geocode input coordinates and see if your service returns a valid location.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Dominoes posted:

Looking for advice on regex in Javascript. I have several different regegexes, and I've been trying to filter the valid one(s) by checking if the result exists. However, Even the invalid ones return a valid array: Just with undefined values on the parts that don't match.

ie:


JavaScript code:
 
var degMinLat = /([NSns])\s*(\d{2})(?:-|\s*)((\d{2})(\.(\d+))|\d{2}(\s|$))?/.exec(lat)
var degMinLon = /([EWew])\s*(\d{3})(?:-|\s*)((\d{2})(\.(\d+))|\d{2}(\s|$))?/.exec(lon)

var degMinLat2 = /([NSns])\s*(\d{1,2})(?:-|\s+)((\d{2})(\.(\d+))|\d{2}(\s|$))?/.exec(lat)
var degMinLon2 = /([EWew])\s*(\d{1,3})(?:-|\s+)((\d{2})(\.(\d+))|\d{2}(\s|$))?/.exec(lon)

etc
I've been checking validity with statements like:

JavaScript code:
if (! degMinLat){}
, and biting off an an arbitrary one that passes. However, even the ones that don't pass pass some matching groups, with others left as undefined. This quietly gives bogus results, and makes testing if a string passes the entire regex a pain. Any suggestions? I suppose I could do some iterating over results and failed flags, but there's got to be a cleaner way

Use the method, 'test' for validity: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

If exec() returns a non-null result then test() returns true.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm running into some JS errors after incorporating dropzone.js into my app. Everything works fine in dev mode (separate & unminified assets) but after I do a real build (JS assets are combined & minified using uglifyjs) I run into "undefined is not a function". So I'm assuming it's something to do with the combine/minify step but I'm having a hard time narrowing it down further.

edit: I added a semicolon to the end of the dropzone.js file and it seems to have fixed the issue...but surely somebody else would have run into that issue if the problem was in fact caused by dropzone.js. So I'm not entirely convinced I have the correct fix, if anybody has some advice for me.

fletcher fucked around with this message at 03:06 on May 20, 2014

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
^^ Looks like it was in fact a bug in the dropzone library: https://github.com/enyo/dropzone/issues/589

Dominoes
Sep 20, 2007

v1nce posted:

When you RegExp your strings, is it expected that your coordinates will always return non-undefined values for the regex matches, or is it OK for the number of "undefined" returns values to fluctuate?
For instance, if you jam in "N32.1234" you might get [32, 1234, undefined] but if I jam in "N32" I get [32, undefined, undefined]. Is the second example still a valid lat/lng?

I can't offer you anything native to make your life easier, but LoDash has a few functions you can use.


I've only skimmed the docs so maybe someone knows something better.

Wheany posted:

Ok, please post some valid examples, and possibly some invalid examples.

It's impossible to go backwards from the posted regexes, because they might have some errors. Also because regexes are a write-only language.

For experimenting, I have used The Regex Coach http://www.weitz.de/regex-coach/

Blinkz0rz posted:

If you're accepting user input for lat/longs you might want to rethink your system.

Is your audience technical enough that they have to input exact coordinates?

If not, maybe you should geocode addresses and not worry about regexing coordinates.

If so, you might want to reverse geocode input coordinates and see if your service returns a valid location.


Wheany posted:

If exec() returns a non-null result then test() returns true.

Thanks dudes! Got it sorted. Your questions prompted me to go back and look at the regexes - they were kind of a mess. The direct solution to my question was probably to add ^ and $ to the regexes, which would reject incomplete matches. I ended up redoing the regexes in a modular way.

The audience is somewhat technical, and would probably stick to one main format. However, I don't want to be a dick and throw an error if they used a hyphen instead of a space, didn't use enough leading 0s, had a degree but not minute etc.

Current implementation:
JavaScript code:
    var cardLat = '([NSns])\\s*'
    var cardLon = '([EWew])\\s*'
    var two = '(\\d{1,2})'
    var three = '(\\d{1,3})'
    var twoDec = '((?:\\d{1,2}\\.\\d+)|(?:\\d{1,2}))'
    var threeDec = '((?:\\d{1,3}\\.\\d+)|(?:\\d{1,3}))'
    var space = '(?:-|\\s+)'

    // ie 'N52', 'e 001.323', 'W1.1'
    var degLat = new RegExp('^' + cardLat + twoDec + '$')
    degLat = degLat.exec(lat)
    var degLon = new RegExp('^' + cardLon + threeDec + '$')
    degLon = degLon.exec(lon)

    // ie 'N52-54.01', 'n 53 23', 'N 52-23', 'n36-7.68', 'W1-04.652'
    var degMinLat = new RegExp('^' + cardLat + two + space + twoDec + '$')
    degMinLat = degMinLat.exec(lat)
    var degMinLon = new RegExp('^' + cardLon + three + space + twoDec + '$')
    degMinLon = degMinLon.exec(lon)

    // ie 's 21-03-6', 'W027 39 49.5', 'N 22-03 54.11'
    var degMinSecLat = new RegExp('^' + cardLat + two + space + two + space + twoDec + '$')
    degMinSecLat = degMinSecLat.exec(lat)
    var degMinSecLon = new RegExp('^' + cardLon + three + space + two + space + twoDec + '$')
    degMinSecLon = degMinSecLon.exec(lon)

    // Only one lat_ should match.
    var lats = [degLat, degMinLat, degMinSecLat]
    for (var i=0; i < lats.length; i++) {
        var lat_ = lats[i]
        if (lat_ !== null) {
            lat_.shift() // Remove first regex result, which is the orig string.
            var resultLat = degMinToDeg.apply(this, lat_)
        }
    }

    var lons = [degLon, degMinLon, degMinSecLon]
    for (var i=0; i < lons.length; i++) {
        var lon_ = lons[i]
        if (lon_ !== null) {
            lon_.shift()
            var resultLon = degMinToDeg.apply(this, lon_)
        }
    }

    return [parseFloat(resultLat), parseFloat(resultLon)]

Dominoes fucked around with this message at 00:17 on May 23, 2014

DholmbladRU
May 4, 2006
Not necessarily a javascript question.. Not sure where to post this. I have built a styled infoBox using the InfoBox plugin for google maps. As part of the infobox there are two columns which are positioned using relative positioning and placed left or right using float:left, or float:right. Strangely when I click on some of the markers and popup the same infobox the right column is sometimes pushed down, even though its using the same exact CSS. See the below images.

http://s24.postimg.org/60olyoa2t/image.jpg
http://s24.postimg.org/ky1odfcp1/image.jpg


Infobox creation

code:
          $(document.body).append('<div id="infobox-wrapper-h"><div class="rounded-corners" id="h-infowindow"><div id="hotel-infowindow-container"><div id="info-header">Washington DC</div><div id="info-intern-wrap"><div style="float:left;" id="left-info"><h5>Information</h5><p class="grey-para">' + json.name + '</p><p class="info-text" style="width:140px">12345 some address washington blvd</p><p class="grey-para">Status</p><p class="info-text">' + json.STATUS + '</p><p class="grey-para">R</p><p class="info-text">234</p><p class="grey-para">Status</p><p class="info-text">' + json.STATUS + '</p><p class="grey-para">Date</p><p class="info-text">openDate</p></div><div id="right-info" style="float: right; position: relative; right: -120px; width: 200px;"><h5>Information</h5>' + Txt + '</div></div></div></div></div>');
     
    IWindow = new InfoBox({
                            content: document.getElementById("infobox-wrapper-h"),
                            disableAutoPan: false,
                            enableEventPropagation: true,
                            pixelOffset: new google.maps.Size(-140, 0),
                            zIndex: null,
                            enableEventPropagation: false,
                            closeBoxURL: '../assets/images/icon.png',
                            boxStyle: {
                                color: 'white',
                                background: '#101010',
                                width: "600px",
                                height: "400px"
                            },
                            infoBoxClearance: new google.maps.Size(1, 1)
                        });

I am out of ideas, as this doesnt happen for every marker...

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
If you're using a 600px-wide fixed size box anyway, you could just set
CSS code:
#info-intern-wrap {
	position:relative;
}
#left-info {
	position:absolute;
	left:0;
	top:0;
	bottom:0;
	width:300px;
}
#right-info {
	position:absolute;
	left:300px;
	top:0;
	bottom:0;
	width:300px;
}
Without any floats.

Dominoes
Sep 20, 2007

Are there any simple JS libraries that include common convenience functions/methods that are omitted from JS?

Ie:
JavaScript code:
function sorted(anArray) {
    return anArray.sort(function(a,b){return a - b})
}


Number.prototype.round = function(places) {
    return +(Math.round(this + "e+" + places)  + "e-" + places);
}


function pad(n, width) {
  n = n + ''
  return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n
}


function radians(angInDegrees) {
    return (angInDegrees*Math.PI) / 180
}


function degrees(angInRadians) {
    return (angInRadians*180) / Math.PI
}

function range(start, stop, step){
    if (typeof stop=='undefined'){
        // one param defined
        stop = start;
        start = 0
    }
    if (typeof step=='undefined'){
        step = 1
    }
    if ((step>0 && start>=stop) || (step<0 && start<=stop)){
        return [];
    }
    var result = [];
    for (var i=start; step>0 ? i<stop : i>stop; i+=step){
        result.push(i);
    }
    return result;
}
etc

Dominoes fucked around with this message at 15:08 on May 25, 2014

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Dominoes posted:

Are there any simple JS libraries that include common convenience functions/methods that are omitted from JS?

Underscore, lodash.

e: Well, okay, those don't include conversion between degrees and radians, but I don't actually think those as something needing a library necessarily. Also sort is a native function in arrays.
e2: and even your example is just "return anArray.sort();" Now I'm completely lost on what you even want.

Wheany fucked around with this message at 11:35 on May 23, 2014

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
There's always php.js! :suicide:

Simply hand pick the PHP functions you want from their semi-impenetrable github repo and you can include them in your project for fun and profit.
There's a wealth of maths functions for you to take advantage of.

I'll be honest, I was joking when I started down this road, but it actually sound like it's what you're after. poo poo.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Wheany posted:

e2: and even your example is just "return anArray.sort();" Now I'm completely lost on what you even want.

No, his version has "sorted", a which compares elements as numbers, instead of Array.prototype.sort sorting elements as strings. Obvious from the name, no?

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?
I don't think I've ever just wanted to sort an array of numbers. I usually need to sort based on some property or something.

Honestly with the library thing, I don't think it's all that necessary. I just add them as you need them. They aren't that complicated to write.

Dominoes
Sep 20, 2007

Looking for thoughts on 'for in' loops in javascript, and this Stack Overlow question on the topic. The accepted answer is that
JavaScript code:
for (var i in myArray) {
    var item = myArray[i]
}
is bad because 1: A libary you loaded might have messed with the array class and 2: you might create an array with only some values filled in.

The way I'm looking at it, this:

JavaScript code:
for (var i=0; i < myArray.length; i++) {
    var item = myArray[i]
}
is enough of an eyesore that it's worth using the cleaner syntax. I have no intention of breaking the array class or defining an array with missing values.

Dominoes fucked around with this message at 15:09 on May 25, 2014

Adbot
ADBOT LOVES YOU

OddObserver
Apr 3, 2009
I don't get how sparse arrays are an argument for using a traditional for over for ... in, seeing how
for ... in actually handles them correctly?

(OTOH, I wonder how well modern JS implementations can compile for ... in; it is a lot harder to
execute efficiently since 'i' is semantically a string on every iteration).

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply