How to do an OR query with rails sunspot for rsolr - sunspot

I'm having trouble finding an example of how to do an OR query with sunspot. Here's my code.
class JobSearch < ActiveRecord::Base
monetize :salary, as: 'salary', allow_nil: true
DEFAULT_DISTANCE_IN_MILES = 50
def search(page, page_size)
latitude, longitude = LatitudeLongitudeLookup.latitude_longitude_from_string(location) if location.present?
Job.search(include: [:state]) do
facet(:minimum_compensation_cents) do
row(150000..Float::INFINITY) do
with(:minimum_compensation_cents).greater_than(150000)
end
row(100000..149999) do
with(:minimum_compensation_cents, 100000..149999)
end
row(50000..99999) do
with(:minimum_compensation_cents, 50000..99999)
end
row(25000..49999) do
with(:minimum_compensation_cents, 25000..49999)
end
end
facet :titles, limit: 5
facet :city_state, limit: 5
facet :job_type
facet :work_remotely
if !include_remote
with(:location).in_radius(latitude, longitude, DEFAULT_DISTANCE_IN_MILES, bbox: true) if latitude && longitude
else #need to do a location with an OR include_remote
with(:location).in_radius(latitude, longitude, DEFAULT_DISTANCE_IN_MILES, bbox: true) if latitude && longitude
#OR - how to do that?
with(:work_remotely, true)
end
with(:city_state, location) if location.present? && (!latitude && !longitude)
order_by_geodist(:location, latitude, longitude) if latitude && longitude
with(:job_type, job_type) if job_type.present?
with(:titles, position_title) if position_title.present?
if !latitude && !longitude && !include_remote
with(:work_remotely, include_remote)
end
fulltext keyword
paginate page: page, per_page: page_size
end
end
end
What I need to do is is directly under the facet section if they have searched on a location and also indicated to include remote jobs, the query should be something like "where location=locationsearchtext OR work_remotely=true". So, how do you construct that with sunspot? Thanks.

This is what you need to do:
facet :work_remotely
if !include_remote
with(:location).in_radius(latitude, longitude, DEFAULT_DISTANCE_IN_MILES, bbox: true) if latitude && longitude
else #need to do a location with an OR include_remote
any_of do
with(:location).in_radius(latitude, longitude, DEFAULT_DISTANCE_IN_MILES, bbox: true) if latitude && longitude
with(:work_remotely, true)
end
end
You can find out more information on the sunspot wiki:
https://github.com/sunspot/sunspot/wiki/Scoping-by-attribute-fields#disjunctions-and-conjunctions

Related

Find location with in 1 mile in postgresql query

I have 2 tables 1 is for facility and 1 is for customer. both contained latitude longitude we want query to fetch customer's available with in 1 miles of facility. We don't want to use postgres function like ST_Distance. Any alternate query to achieve it.
Iterate java list of location and used haversine formula to calculate distance in miles
private double distance(double LatOne, double LonOne, double LatTwo, double LonTwo) {
LonOne = Math.toRadians(LonOne);
LonTwo = Math.toRadians(LonTwo);
LatOne = Math.toRadians(LatOne);
LatTwo = Math.toRadians(LatTwo);
double deltaLon = LonTwo - LonOne;
double deltaLat = LatTwo - LatOne;
double formula = Math.pow(Math.sin(deltaLat / 2), 2)+ Math.cos(LatOne) * Math.cos(LatTwo)* Math.pow(Math.sin(deltaLon / 2),2);
double fOutput = 2 * Math.asin(Math.sqrt(formula));
return (fOutput * 3956) ;
}

How to update value of an dataframe if it satisfies a specific condition inside a nested loop in spark scala

sammple datajust need to know how can we update values inside a df with specific condition.
My Df contains some store related data, like store id, store name, Address, latitude, longitude ..
I need to find radius using this latitude and longitude
sqrt((x1-x2)^2) +((y1-y2)^2))
x1= 1st row latitude, x2 =2nd row latitude, like wise longitude also.
here I need to compare each store with other stores, so a nested loop.
So I converted Latitude and Longitude as lists and with the help of these 2 lists am doing the iteration
I have added new columns Radius and New_ID already
after running this the value of result is not getting updated in the dataframe,
please help me out,
If any more details required please let me know
while (i<latlist.length-1)
{
j=1
id=id+1
while(j<longlist.length)
{
result = sqrt(pow(latlist(i)- latlist(j),2) + pow(longlist(i) - mylonglist(j),2))
df3=df2.withColumn("Radius", col("Radius")+result)
} j=j+1;
df4= df3.filter(df3("Radius")<=1.32).withColumn("New_ID", col("New_ID")+id)
}
i=i+1
}
df4.show(10)
}
Sample Data
StoreName StoreReg Latitude Longitude Radius New_ID
Abc MH 50.5684 6.9894 0 0
Xyz DE 47.9783 7.4984 0 0
Pqr AS 67.8479 10.7029 0 0
Qwr LI 53.8733 8.8393 0 0
Dsg GY 49.0832 9.78946 0 0
Hnr TY 51.8937 8.5678 0 0
Erf ER 52.7689 7.9763 0 0

How do I round a number to the nearest 5 in my coffee script file?

I have a restaurant recommendation app, built in Rails 4.2, and using Mithril.Js. When user searches for a restaurant, I tell him how many results I found using the code below.
How do I adapt this to show him the number of results rounded up to the nearest 5 (if <10 results), and to the nearest 10 (if <100 results), and to the nearest 100 (if <1000 results)?
RESTAURANTS.COFFEE FILE
App.c.restaurants =
controller: ->
loadMore: ->
loading = true
pubsub.publish 'search', page: store[store.length-1].page+1
view: (ctrl) ->
head = if loading
'Calculating...'
else if store.length
"About #{store[0].totals || 0} restaurants"
else
''
Here is a simple function you could define
round_to_nth = (number, nth) ->
if number % nth >= (nth/2) then parseInt(number / nth) * nth + nth else parseInt(number / nth) * nth
and use
"About #{round_to_nth(store[0].totals, 100) || 0} restaurants" # for nearest 100th
"About #{round_to_nth(store[0].totals, 5) || 0} restaurants" # for nearest 5th

Total distance of route using Leaflet routing machine in rMaps/rCharts

I would like to produce a shiny app that asks for two addresses, maps an efficient route, and calculates the total distance of the route. This can be done using the Leaflet Routing Machine using the javascript library, however I would like to do a bunch of further calculations with the distance of the route and have it all embedded in a shiny app.
You can produce the map using rMaps by following this demo by Ramnathv here. But I'm not able to pull out the total distance travelled even though I can see that it has been calculated in the legend or controller. There exists another discussion on how to do this using the javascript library - see here. They discuss using this javascript code:
alert('Distance: ' + routes[0].summary.totalDistance);
Here is my working code for the rMap. If anyone has any ideas for how to pull out the total distance of a route and store it, I would be very grateful. Thank you!
# INSTALL DEPENDENCIES IF YOU HAVEN'T ALREADY DONE SO
library(devtools)
install_github("ramnathv/rCharts#dev")
install_github("ramnathv/rMaps")
# CREATE FUNCTION to convert address to coordinates
library(RCurl)
library(RJSONIO)
construct.geocode.url <- function(address, return.call = "json", sensor = "false") {
root <- "http://maps.google.com/maps/api/geocode/"
u <- paste(root, return.call, "?address=", address, "&sensor=", sensor, sep = "")
return(URLencode(u))
}
gGeoCode <- function(address,verbose=FALSE) {
if(verbose) cat(address,"\n")
u <- construct.geocode.url(address)
doc <- getURL(u)
x <- fromJSON(doc)
if(x$status=="OK") {
lat <- x$results[[1]]$geometry$location$lat
lng <- x$results[[1]]$geometry$location$lng
return(c(lat, lng))
} else {
return(c(NA,NA))
}
}
# GET COORDINATES
x <- gGeoCode("Vancouver, BC")
way1 <- gGeoCode("645 East Hastings Street, Vancouver, BC")
way2 <- gGeoCode("2095 Commercial Drive, Vancouver, BC")
# PRODUCE MAP
library(rMaps)
map = Leaflet$new()
map$setView(c(x[1], x[2]), 16)
map$tileLayer(provider = 'Stamen.TonerLite')
mywaypoints = list(c(way1[1], way1[2]), c(way2[1], way2[2]))
map$addAssets(
css = "http://www.liedman.net/leaflet-routing-machine/dist/leaflet-routing-machine.css",
jshead = "http://www.liedman.net/leaflet-routing-machine/dist/leaflet-routing-machine.js"
)
routingTemplate = "
<script>
var mywaypoints = %s
L.Routing.control({
waypoints: [
L.latLng.apply(null, mywaypoints[0]),
L.latLng.apply(null, mywaypoints[1])
]
}).addTo(map);
</script>"
map$setTemplate(
afterScript = sprintf(routingTemplate, RJSONIO::toJSON(mywaypoints))
)
# map$set(width = 800, height = 800)
map
You can easily create a route via the google maps api. The returned data frame will have distance info. Just sum up the legs for total distance.
library(ggmap)
x <- gGeoCode("Vancouver, BC")
way1txt <- "645 East Hastings Street, Vancouver, BC"
way2txt <- "2095 Commercial Drive, Vancouver, BC"
route_df <- route(way1txt, way2txt, structure = 'route')
dist<-sum(route_df[,1],na.rm=T) # total distance in meters
#
qmap(c(x[2],x[1]), zoom = 12) +
geom_path(aes(x = lon, y = lat), colour = 'red', size = 1.5, data = route_df, lineend = 'round')

iPhone - How do i get direction with degree based location

First I've implemented location manager functions in my class and whict are working fine, and gives me the current location. From that location I got how to get location degrees from here. but I'm not able to get the direction (i.e. North, South, East, West) I've referred this too. I want the location that I'm getting to be displayed in degrees with direction format like this. i.e. location manager gives me +37.33019332,-122.02298792 and i want something like 37° 19' 49"N, -122° 1' 23"E. I'm getting all things just don't know how to get the last "N" and "E".
If i use CLLocation.course for this I'm getting my direction course.
Any help would be appreciated.
This is actually very simple. Latitudes begin at 0° at the equator with the north pole being 90.0 and the south pole being -90.0. Basically, if the latitude is between 0 and 90, you're in the northern hemisphere and the southern hemisphere for latitude between 0 and -90.
Longitude basically works the same way. 0° refers to the prime meridian which is the imaginary line that runs through Greenwich, England and a part of Africa. A positive longitude up to 180° refers to locations east of the prime meridian, while negative longitudes refer to areas west of the prime meridian up to 180°.
Use this code and put CLLocationManagerDelegate at .h file
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
updatedHeading = newHeading.magneticHeading;
float headingFloat = 0 - newHeading.magneticHeading;
rotateImg.transform = CGAffineTransformMakeRotation(headingFloat*radianConst);
float value = updatedHeading;
if(value >= 0 && value < 23)
{
compassFault.text = [NSString stringWithFormat:#"%f° N",value];
}
else if(value >=23 && value < 68)
{
compassFault.text = [NSString stringWithFormat:#"%f° NE",value];
}
else if(value >=68 && value < 113)
{
compassFault.text = [NSString stringWithFormat:#"%f° E",value];
}
else if(value >=113 && value < 185)
{
compassFault.text = [NSString stringWithFormat:#"%f° SE",value];
}
else if(value >=185 && value < 203)
{
compassFault.text = [NSString stringWithFormat:#"%f° S",value];
}
else if(value >=203 && value < 249)
{
compassFault.text = [NSString stringWithFormat:#"%f° SE",value];
}
else if(value >=249 && value < 293)
{
compassFault.text = [NSString stringWithFormat:#"%f° W",value];
}
else if(value >=293 && value < 350)
{
compassFault.text = [NSString stringWithFormat:#"%f° NW",value];
}
}