Dealing with Geospatial data is cumbersome and at the same time, it is fun. Developers who do it for the first time might enter some road blockers but as you progress it gives a joy of learning. GIS stands for Geographic information system which deals with gathering, mapping and analyzing geospatial data. But it is not as easy as it sounds. Let me walk through you the challenges that I have faced recently in my project:

Requirement: Import existing polygons information and map that given latitude and longitude with the polygon.

Challenge-1: Understanding the basics and jargon

Since I am doing for the first time, like what SRID should I use, what datatype should I use, what coordinate system should I use? After thorough research I end up using srid 4326, multipolygon datatype and WGS 84 coordinate system.

Many of you might not understand what WGS 84 means? WGS 84 stands for World Geodetic System is kind of survey (standard) which was done on the year 1984. There are different kinds of standards that are exists currently like WGS 72, WGS 66 and WGS 60 etc. These are the surveys(standards) that are conducted in those respective years by making some assumptions about earth. So, for example if we calculate India location using WGS 84 is might be different if we calculate using WGS 72.

SRID stands for Spatial Reference System Identifier which tells us about the coordinate system we were using while gathering spatial data.

Challenge-2: Data importing

Since we are using rails powered with postgresql, importing data into database is quite easy but not in this case as we got information in geojsonformat which I never seen before. Fortunately, ruby provides a gem called rgeo-json which makes our life easy. Following is the code snippet that I have written to import geojson data.

@geo_factory = RGeo::Geographic.spherical_factory(srid: 4326)f = RGeo::GeoJSON.decode(
File.open(<geojson file path>).read,
geo_factory: @geo_factory)
)
f.each do
polygon
Polygon.new(geopolygon: polygon.geometry).save
end

where polygon is our model. Here is our migration file looks like:

add_column :polygons, :geopolygon, :multi_polygon, srid: 4326 

Challenge-3: Map point with Polygon using sql query

PostGIS is a postgres database extension which enables postgres to make spatial calculations. To find that given point lies which polygon we need to make use of st_contains function. To use st_contains, first we have to make sure whether two geometries should use same SRID or not ie., in our case it is 4326. Since in my database we are storing latitude and longitude as float columns, first we need to typecast them to as a POINT and set SRID to 4326 as follows:

# Returns geometry of a given point.
ST_SetSRID(ST_POINT(<longitude>, <latitude>), 4326)

Now final query to find appropriate polygon:

Polygon.where("st_contains(geopolygon, 
ST_SetSRID(ST_Point(<long>,<lat>), 4326)
) = true").first

Though it took time to complete requirement but at the end I felt I have done something different than what I usually do. I hope this article would throw some light about GIS.

Original Source: https://medium.com/@learnitnow/gis-on-rails-23513c15de7c

GoLang Interface and Polymorphism GoLang Interface and Polymorphism

Go is a programming language created at Google in 2009 by Robert Griesemer, Rob Pike, and Ken Thompson. It’s very easy to learn, and yet incredibly powerful, especially for concurrency. Apps built on this language can perform better than most of the other languages for similar purpose especially against dynamically typed language like PHP, ruby, python.,

We at West Agile Labs can help you leverage the latest technologies through our custom software development services!

Go is a decent choice for writing servers that handle thousands of queries per second with latencies of a few milliseconds.

Since Go as a programming language is a great choice to learn but the concept of object-oriented programming is revisited in Golang. Go language does not have the concept of class(instead it contain Struct), does not have support for inheritance(instead of support composition). Go language has been criticised for lack of generic support.

Go doesn’t have the classic Object Oriented concept of classes and inheritance. Interfaces in Go provide a way to specify the behavior of an object: do like this and reuse it.

In Go programming language Interfaces are types that just define a set of methods (the method set), but these methods do not contain code. This method is never implemented by the interface type directly. Also, an interface cannot contain variables. Go’s interface type provides a lot of extensibility and compos-ability for Go applications. Interface types express generalizations or abstractions about the behaviors of other types.

Here the key features of Go Lang:

  1. Code transparency: With Go, you will know exactly with the code is doing and will be able to accurately estimate how much time and memory it is utilizing. Go Lang follows a standard code format generated by the FMT tool automatically. 
  1. Minimalist language: Go is a simple language that follows a minimalistic approach. Thereby, for new developers the learning curve to not too steep. A few basic, orthogonal features compose the core Go language that can be combined in a relatively limited number of ways. This makes learning the language and reading and writing programs simpler. Expert programmers can learn the language from the specifications themselves and Go provides automatically generated documentation keeping the interface minimal with very little to learn.
  1. Better Performance: The performance of Go Lang is enhanced by its standard libraries that provide optimized code derived from efficient algorithms. It stands against any memory leads with the garbage collected feature. Just like C or C++, go does not need any interpretation as it is a compiled language and by doing away with an interpreted your Go-built app will be more error-free. In terms of system requirements, this language is not very demanding, this means that users with older devices can also access your application.
  1. Supports Testing: Go Lang combines unit testing and coding.  It offers an easy mechanism for writing your unit tests with your code in parallel. The tool also assists in interpreting the code coverage through your tests, benchmarking tests, and writing sample code used to produce your code documentation.

Comparing instance of Java with Go lang, Java interface must be explicitly implemented by Java-like shown below:


public class Foo implements InterfaceName{
}

In Golang, the interface is not implemented explicitly like java but satisfied by type method.

Go also doesn’t have the typical class-like inheritance you’re normally used to, but it does have a couple of things that are pretty close.


# interface_demo.go
package main
import "fmt"
type Foo struct {
	}
func (f Foo) String() string  {
	return fmt.Sprintf("Empty Foo")
}
func main()  {
	f := Foo{}
	fmt.Println(f)
}

When I run above code with the command `go run interface_demo.go`, it will print `Empty Foo`

As I have already mentioned that Golang does not class instead it has type and struct. On above example, method ‘string’ added to Foo struct. ‘String()’ method is defined inside stringer interface defined in Golang. fmt.Printf calls the String method if available (checks if the provided variable satisfies Stringer interface).

Now we are going see(below code) how to duck type one subtype into superclass. We can substitute the struct variable with `interface` variable since all struct implements interface defined function.


package main
import "fmt"
type Animal interface{
	walk()
}
type Human struct  {
	}
type Dog struct {
}
func (Human) walk(){
	fmt.Println("its human walking")
}
func (Dog) walk(){
	fmt.Println("its Dog	 walking")
}
func printall_walker(a [] Animal){
  for _, a := range a {
  	a.walk()
  }
}
func main()  {
	printall_walker([] Animal{Human{}, Dog{}})
}

As seen above, Animal is an interface where method `walk` has been defined. Human and Dog struct added walk method, its mean implicitly implemented `Animal` interface. As we can see, now Human and Dog can be passed into Animal interface object.

We at West Agile Labs provide excellent custom software development services. Start your Project with us now!

Originally published in https://narutosanjiv.wordpress.com

Effective querying using SQL over Rails Effective querying using SQL over Rails

Most of the rails developers write queries on daily basis. Some of the other day by mistake we follow rails way instead of SQL way to do tasks like sorting etc. But you might ask what’s the problem regarding which approach I take as long as I am able to get correct results. Yes, you may get correct results but you will end up with performance problems in future. Following a set of scenarios I am observed that SQL querying out powered rails:

1) Apply sorting on a combination of different tables:

I have three tables namely deposits, purchases and withdraws. Now, I want to display latest three records from a combination of three tables.

Let’s check rails way

Benchmark.ms do 
  (Deposit.all + Purchase.all + Withdraw.all).sort do |x, y|       x.updated_at <=> y.updated_at
  end
end
Deposit Load (0.6ms) SELECT "deposits".* FROM "deposits"
Purchase Load (0.4ms) SELECT "purchases".* FROM "purchases" 
Withdraw Load (0.7ms) SELECT "withdraws".* FROM "withdraws"
=> 121.91500002518296

Let’s check SQL way

SELECT 'deposit', authorization_code, amount, status, updated_at FROM DEPOSITS 
ORDER BY updated_at 
DESC LIMIT 3)
UNION
(SELECT 'purchase', ref, amount, status, updated_at FROM PURCHASES ORDER BY updated_at 
DESC LIMIT 3) 
UNION
(SELECT 'withdraw', ref, amount, status, updated_at FROM WITHDRAWS ORDER BY updated_at 
DESC LIMIT 3)
ORDER BY updated_at DESC LIMIT 3
=> SQL (2.0ms)

2) Apply sorting on different types of data:

Let’s say a table stores gifs, videos of different duration. Now I want sort videos, gifs in ascending order of content duration separately.

Let’s check rails way

Benchmark.ms do 
   videos = SpotBooking.where(content_type:'video')
                       .order('content_duration DESC')
gifs = SpotBooking.where(content_type:'gif')
                     .order('content_duration DESC')
videos + gifs 
end
 
SpotBooking Load (0.4ms) SELECT "spot_bookings".* FROM "spot_bookings" WHERE "spot_bookings"."content_type" = $1 ORDER BY content_duration DESC [["content_type", 3]]
SpotBooking Load (0.4ms) SELECT "spot_bookings".* FROM "spot_bookings" WHERE "spot_bookings"."content_type" = $1 ORDER BY content_duration DESC [["content_type", 2]]
=> 12.477000011131167

Let’s check SQL way

SELECT id, content_duration, row_number() 
OVER (PARTITION BY content_type ORDER BY content_duration DESC) 
FROM spot_bookings
=> SQL (0.8ms)

3) Formatting the data while querying:

Let’s check rails way:

Benchmark.ms do 
  h = {} 
  pricings = SpotPricing.order('starts_at ASC') 
  pricings.each do |b|    
    h[b.starts_at.strftime("%H %M %P")] = b.price.to_f 
  end 
end
SpotPricing Load (0.5ms) SELECT "spot_pricings".* FROM "spot_pricings" ORDER BY starts_at ASC
=> 35.459000151604414
# output
{"02:19 AM"=>"1.00", "03:19 AM"=>"2.00", "04:19 AM"=>"3.00",  
 "05:19 AM"=>"4.00", "06:19 AM"=>"5.00", "07:19 AM"=>"6.00", 
 "08:19 AM"=>"7.00", "09:19 AM"=>"8.00", "10:19 AM"=>"9.00",
 "11:19 AM"=>"10.00", "12:19 PM"=>"11.00", "13:19 PM"=>"12.00",  "14:19 PM"=>"13.00", "15:19 PM"=>"14.00", "16:19 PM"=>"15.00",  "17:19 PM"=>"16.00", "18:19 PM"=>"17.00", "19:19 PM"=>"18.00", "20:19 PM"=>"19.00", "21:19 PM"=>"20.00", "23:19 PM"=>"22.00", "00:19 AM"=>"23.00"}

Let’s check SQL way:

SpotPricing.order('starts_at ASC').pluck("to_char(starts_at, 'HH24:MI AM')", "to_char(price, 'FM999999999.00')")
SELECT to_char(starts_at, 'HH24:MI AM'), to_char(price, 'FM999999999.00') FROM "spot_pricings" ORDER BY ASC
=> SQL (0.5ms)
# Output
{"02:19 AM"=>"1.00", "03:19 AM"=>"2.00", "04:19 AM"=>"3.00", 
 "05:19 AM"=>"4.00", "06:19 AM"=>"5.00", "07:19 AM"=>"6.00", 
 "08:19 AM"=>"7.00", "09:19 AM"=>"8.00", "10:19 AM"=>"9.00", 
 "11:19 AM"=>"10.00", "12:19 PM"=>"11.00", "13:19 PM"=>"12.00",    "14:19 PM"=>"13.00", "15:19 PM"=>"14.00", "16:19 PM"=>"15.00", "17:19 PM"=>"16.00", "18:19 PM"=>"17.00", "19:19 PM"=>"18.00", "20:19 PM"=>"19.00", "21:19 PM"=>"20.00", "23:19 PM"=>"22.00", "00:19 AM"=>"23.00"}

In all above scenarios, SQL plays best compared to conventional rails way. Sometimes I would feel it’s not a big deal if you not follow design patterns as long as your ability to provide the best outcome.

Any suggestions and feedback would be welcome!!!

Happy querying!!!


Originally published at railslearning.wordpress.com on July 31, 2017.