Monday, February 10, 2020

Javascript program - Split array of numbers into two (numbers less than 12 and numbers greater than 12)

Javascript - Split array of numbers into two...

This JS code will return (lessThan_12) for numbers less than 12 from the given array of numbers and numbers greater than 12 as (greaterThan_12).


// Define the array...
const array_of_numbers = [10, 2, 34, 11, 5, 9, 100, 23, 29, 56, 3, 4, 50, 12, 7, 8];

// Define empty arrays to hold the two expected arrays...
let greaterThan_12 = [];
let lessThan_12 = [];

// Using 'for each' loop to loop over the array's element and push relevant to empty array
array_of_numbers.forEach(runFunc);

function runFunc(x) {
 if (x > 12){
  greaterThan_12.push(x);
 } else if (x < 12) {
  lessThan_12.push(x);
 }
}

// Lets see what is in each array...?
console.log(greaterThan_12);
console.log(lessThan_12);



The comment has explained everything in the script :). The only difficult part that may require some explanation is the forEach() loop, which takes a function 'runFunc()' that performs the magic.


Note: if you want 12 to be included in either arrays use >= "greater than or equal to" or <= "less than or equal to". If you use both, only the first case will be applied.

// Define the array...
const array_of_numbers = [10, 2, 34, 11, 5, 9, 100, 23, 29, 56, 3, 4, 50, 12, 7, 8];

// Define empty arrays to hold the two expected arrays...
let greaterThan_12 = [];
let lessThan_12 = [];

// Using 'for each' loop to loop over the array's element and push relevant to empty array
array_of_numbers.forEach(runFunc);

function runFunc(x) {
 if (x >= 12){
  greaterThan_12.push(x);
 } else if (x <= 12) {
  lessThan_12.push(x);
 }
}

// Lets see what is in each array...?
console.log(greaterThan_12);
console.log(lessThan_12);


Sunday, February 9, 2020

JavaScript Program - what year will age be 100 years old?

This will be a simple javascript program that uses HTML form to ask users to enter their name and their age. Then it will evaluate the age and print out a message addressed to them that tells them the year that they will turn 100 years old :). And if they are already 100 years old, it will display a different message telling them they have already attained 100 years of age.



So, it is a simple JavaScript code to calculate when an age will be 100 years old. The HTML form as seen above will consist of basic text labels and inputs.

The primary objective of the exercise is to show how to interact with the DOM:-
1- Get text from input box
2- Process the text values and
3- Write the processed text to HTML page





The JS Code

<!DOCTYPE html>
<html>
<head>
 <title>100 years....</title>
</head>
<body style = "text-align:center;">

 <hr>
 <!-- The form start -->
 <label>Name: </label> <input type="text" id="name">
 <label>Age: </label> <input type="number" id="age">
 <button onclick="fun100()">Submit</button>

 <hr>
 <p id="p" style="font-size: 20px; color: gray;"></p>
 <!-- The form end -->

 <script>

  function fun100() {
   // Get the input values into variables...
   let name = document.getElementById('name').value;
   let age = document.getElementById('age').value;

   // Grab the current year...
   var current_date = new Date();
     var current_year = current_date.getFullYear();


   // calculate the year input age will be 100...
   let year = (current_year - age) + 100


   // Check if age is above 100 and write appropraite option to DOM..
   if (age >= 100){
    document.getElementById('p').innerHTML = name + " has already attained 100 years old";
   } else{
    document.getElementById('p').innerHTML = name + " will be 100 years old in the year " + year
   }

  }

 </script>

</body>
</html>






Tuesday, February 4, 2020

Working with GeoJSON and GeoPandas


GeoJSON is an extension of regular JSON data structure that supports geographic/geometry types, such as: Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, and GeometryCollection.

GeoPandas is an open source project to make working with geospatial data in python easier. GeoPandas extends the datatypes used by pandas to allow spatial operations on geometric types, (geopandas.org, 2020).

Typically, GeoPandas is used to read GeoJSON data into a DataFrame as seen below. This is same process you will read regular JSON into Pandas dataframe.

import geopandas as gpd
nigerian_states = gpd.read_file(r"C:\Users\Yusuf_08039508010\Desktop\ng_State.geojson")
nigerian_states.head()



Because geopandas works with geospatial data, you can easily plot the data which generates a plot of the GeoDataFrame with matplotlib.  If a column is specified, the plot coloring will be based on values in that column.

%matplotlib inline
nigerian_states.plot(column='state_name', legend=True, figsize=(15, 15))
%matplotlib inline: makes sure that the plot displays in jupyter notebook
column='state_name': color is achieved by specifying the column name
legend=True: legend is set to true to display it since default setting is false
figsize=(15, 15): figure can be altered.





The full map is as seen below...



Label the polygons with the state's name column.

%matplotlib inline
ax = nigerian_states.plot(column='state_name', legend=True, figsize=(15, 15))
map = nigerian_states.apply(lambda x: ax.annotate(s=x.state_name, xy=x.geometry.centroid.coords[0], ha='center'),axis=1)





Geopandas can read almost any vector-based spatial data format including ESRI shapefile, GeoJSON, KML, AutoCAD DXF/DWG, SpatialLite, GML, Geopackage files and more.




Monday, February 3, 2020

Reserved keywords in Python, Javascript and R

These are a set of words that have special meaning and cannot be used as an identifier (that is as variable name, function name, class name etc.). These are the building block of Python, Javascript and R programming languages

Avoid using these reserved words and keywords as function or variable names as Python, JavaScript and R has reserved these words for their own use.


List of reserved keywords in Python

['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']





List of reserved keywords in JavaScript
abstractargumentsawait*boolean
breakbytecasecatch
charclass*constcontinue
debuggerdefaultdeletedo
doubleelseenum*eval
export*extends*falsefinal
finallyfloatforfunction
gotoifimplementsimport*
ininstanceofintinterface
let*longnativenew
nullpackageprivateprotected
publicreturnshortstatic
super*switchsynchronizedthis
throwthrowstransienttrue
trytypeofvarvoid
volatilewhilewithyield
Words marked with* are new in ECMAScript 5 and 6. (Source: https://www.w3schools.com/js/js_reserved.asp)


List of reserved keywords in R

if, else, repeat, while, function, for, in, next, break, TRUE, FALSE, NULL, Inf, NaN, NA, NA_integer_, NA_real_, NA_complex_, NA_character_





Checking for reserved keywords

The above keywords may get altered in different versions of Python, JavaScript and R. Some extra might get added or some might be removed. So, how do you look-up for these reserved words in either Python, JavaScript or R?

You can always get the list of keywords in your current version as follow:-


Checking for reserved keywords in Python

import keyword
print(keyword.kwlist)
In python interpreter, run the above lines to view the list.



Checking for reserved keywords in JavaScript

Unlike in python and R, I am not sure javascript has a way to call a built-in function to display its available reserved keywords. So, you need to check a reliable archive such as the Mozilla Developer Doc for up to date list of reserved keywords in javascript.



Checking for reserved keywords in R

To check for the keywords, type the following at the R command prompt as follows.

help(reserved)
or

?reserved

Thank you for reading.

Saturday, February 1, 2020

Google Maps APIs and services

API  also know as "Application Programming Interface" is a medium that allows a script to communicate with some data sets host somewhere on a remote or local server.

In this case, Google has collected huge amount of data (most especially those data that relates to making and using maps) over the years.

Now, different clients or users across the world needs to access and make use of these data already collected by Google. So instead of these users passing through the pain of collecting these data by themselves, they will ask google to give them access to such data.

This is where an API comes into play. Via API, Google has exposed various map data to its users under various names. Here below are some of the Google API that are most useful in the GIS industry.


Google Maps APIs
Google has about 16 Maps APIs as seen below...


Distance Matrix API - Travel time and distance for multiple destinations.


Places API - Get detailed information about 100 million places


Maps SDK for Android - Maps for your native Android app.


Maps Embed API - Make places easily discoverable with interactive Google Maps.


Street View API - Real-world imagery and panoramas.


Places SDK for iOS - Make your iOS app stand out with detailed information about 100 million places


Maps JavaScript API - Maps for your website


Maps Elevation API - Elevation data for any point in the world.


Roads API - Snap-to-road functionality to accurately trace GPS breadcrumbs.


Places SDK for Android - Make your Android app stand out with detailed information about 100 million places


Geolocation API - Location data from cell towers and WiFi nodes.


Maps SDK for iOS - Maps for your native iOS app.


Maps Static API - Simple, embeddable map image with minimal code.


Directions API - Directions between multiple locations.


Time Zone API - Time zone data for anywhere in the world.


Geocoding API - Convert between addresses and geographic coordinates.