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.

Tuesday, January 21, 2020

Capitalize first character of a given string in Python and JavaScript

Lets take a look at how we can capitalize first character of a given string/phrase in both Python and JavaScript.

Assuming we have a string like this: 'bOY in LOVE' and we needed it transform properly to 'Boy in love'.


Python solution

In python, there is a built-in method to getting it done called capitalize().
So, all that is required is to call the capitalize() method on the string like this:

'bOY in LOVE'.capitalize()    



Lets assume, we are not aware the capitalize() method existed. Here is how we can construct one using the upper() and lower() methods.



def capitalize_fun(s):
    # checks if it is a string
    if type(s) is not str: 
        return ''
    else:
        return s[0].upper() + s[1:].lower()
    
capitalize_fun('bOY in LOVE')





JavaScript solution

Unlike python, JavaScript doesn't have a built-in method for doing this (at least as at the time of writing - 20/01/2020), so we have to use the concept above to write.

const capitalize = (s) => {
  if (typeof s !== 'string') return ''
  return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase()
}

console.log(capitalize('bOY in LOVE'))





That is it!


Monday, January 20, 2020

Convert HEXEWKB to Latitude/Longitude in python


from shapely import wkb

hexlocation_list = ["0101000020E6100000AECB9307F9D812400F2ADCE003704940", 
                    "0101000020E6100000E40AAE6CD6DA1240941F95531C704940", 
                    "0101000020E6100000C0D7C68E7CD81240F550364044704940", 
                    "0101000020E6100000CB752BC86AC8ED3FF232E58BDA7E4440", 
                    "0101000020E6100000DB81DF2B5F7822C0DFBB7262B4744A40"]


for hexlocation in hexlocation_list:
    point = wkb.loads(hexlocation, hex=True)
    
    longitude, latitude = point.x, point.y
    print(longitude, latitude)





Related articles:
1- How to convert HEXEWKB to Latitude, Longitude (in python)?


Monday, January 13, 2020

Making the Map of 10 States Ready To Pay N30,000 Minimum Wage

President Buhari had in April 2019 signed the new wage bill aimed at boosting the morale of the Nigerian workers into law.

According to Nigeria Labour Congress (NLC), only ten (10) states listed below met the December 31, 2019 deadline set by organised labour. NLC had on December 11, 2019 at a meeting with its state chairmen in Abuja, set December 31 of the same year for all state governors to conclude negotiations with workers in their states following an agreement with the Federal Government on October 18, 2019.

As GIS practitioners, lets visualize these 10 states on a map to see if we can deduce any spatial pattern!

The 10 states are:-

  • Abuja (Federal Level)
  • Adamawa
  • Bauchi
  • Borno
  • Jigawa
  • Kaduna
  • Kano
  • Katsina
  • Kebbi
  • Lagos and
  • Ebonyi



Mapping Steps

Step 1:
Get the vector map of Nigeria in shapefile format. You can download one from HERE (State, LGA and Wards) or from GADM Data web portal.



Step 2:
Load the state shapefile into your favorite GIS software, here I will use QGIS.


Step 3:
Select the 10 states from the list above that met the NLC December 31, 2019 minimum wage deadline.

You can do this selection from the attribute table or by simply selecting from the map directly. Then give them a different color from the remaining states.

Here I will use green color for states that met with the deadline and white for those that didn't.



To make the selection the query will look like this: "state_name" in  ('fct', 'Adamawa', 'Bauchi', 'Borno', 'Jigawa', 'Kaduna', 'Kano', 'Katsina', 'Kebbi', 'Lagos', 'Ebonyi')

The final map as seen below:-


From the resulting map, there are some spatial patter readily seen such:-

  • Most of the northern states responded to the deadline.
  • Most of the wealthy states with oil wells failed to met up with the deadline.
  • States with larger land mass responded well
  • ect

We can now begin to ask some spatial related questions to uncover some possible reasons why it was easy for these states to met the 30,000 wage on time.

  • Does this has to do with the states low/high population?
  • Does it has to do with the states' generated revenue?
  • Does it means the Governors of those states have more sympathy for it's workers?
  • Or cold it be because the states are oil producing states and receives high allocation from you he federal government?
  • etc
Off curse, this is simple case map that a graphic oriented software such as coreldraw or photoshop can easily do. But think Spatially to uncover hidden information!

Thursday, January 9, 2020

City-Data.com Zip Codes Data Wrangling

Here I found myself working data collection from City-Data.com where we needed to three variables ('Median year house/condo built', 'Median household income', 'Median house or condo value' and 'Median resident age') for a few hundred zip codes as seen below.



There are several polygons that makeup a zip code, so an average value for all the variable is what we needed.

The raw data collected from the web page is like this:-
55388
2004
Median household income: $74,048
Median house or condo value: $158,600
Median resident age: 30.8
1976
Median household income: $74,583
Median house or condo value: $305,400
Median resident age: 48
1962
Median household income: $68,958
Median house or condo value: $218,900
Median resident age: 41.7
1994
Median household income: $58,587
Median house or condo value: $172,900
Median resident age: 39.5
1997
Median household income: $94,042
Median house or condo value: $233,300
Median resident age: 36.7
1986
Median household income: $138,917
Median house or condo value: $446,200
Median resident age: 39.9
2000
Median household income: $104,125
Median house or condo value: $263,800
Median resident age: 34.6

The expected output from above that will be used in excel average function is like this:-

55388
=AVERAGE(2004, 1976, 1962, 1994, 1997, 1986, 2000)
=AVERAGE(74048, 74583, 68958, 58587, 94042, 138917, 104125)
=AVERAGE(158600, 305400, 218900, 172900, 233300, 446200, 263800)
=AVERAGE(30.8, 48, 41.7, 39.5, 36.7, 39.9, 34.6)

Friday, December 6, 2019

Convert list comprehension to for loop in python

Lets see the concept of going from 'list comprehension' to 'for loop'.




Above is a nested python list of list that contains names of countries. The list comprehension returns the names of countries with less than ten characters.

Lets try to 'incomprehension' the list :)... more like trying to decompress it into for loop!

The "ten_character" list will start as an empty list then we append the filtered result to it from the for loops.

So, the arrangement is to take the first for loop, follow by the second for loop, then the if conditional statement and then append the result at the end. See the script below...







The complete source code:-

# List of countries...
countries = [['San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Georgia and the South Sandwich Islands'], 
             ['Nepal', 'Netherlands', 'Netherlands Antilles', 'New Caledonia', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Niue', 'Norfolk Island', 'North Korea', 'Northern Mariana Islands', 'Norway'], 
             ['Togo', 'Tokelau', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Turks and Caicos Islands', 'Tuvalu', 'U.S. Minor Outlying Islands', 'U.S. Virgin Islands', 'Uganda', 'Ukraine', 'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatican City', 'Venezuela', 'Vietnam', 'Wallis and Futuna', 'Western Sahara'], 
             ['Afghanistan', 'Albania', 'Algeria', 'American Samoa', 'Andorra', 'Angola', 'Anguilla', 'Antarctica', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Aruba', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bermuda', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Bouvet Island', 'Brazil', 'British Indian Ocean Territory']]

# Country name less than 10 character lenght...
ten_character = [ten for sublist in countries for ten in sublist if len(ten) < 10]

print(ten_character)


# List of countries...
countries = [['San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Georgia and the South Sandwich Islands'], 
             ['Nepal', 'Netherlands', 'Netherlands Antilles', 'New Caledonia', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Niue', 'Norfolk Island', 'North Korea', 'Northern Mariana Islands', 'Norway'], 
             ['Togo', 'Tokelau', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Turks and Caicos Islands', 'Tuvalu', 'U.S. Minor Outlying Islands', 'U.S. Virgin Islands', 'Uganda', 'Ukraine', 'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatican City', 'Venezuela', 'Vietnam', 'Wallis and Futuna', 'Western Sahara'], 
             ['Afghanistan', 'Albania', 'Algeria', 'American Samoa', 'Andorra', 'Angola', 'Anguilla', 'Antarctica', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Aruba', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bermuda', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Bouvet Island', 'Brazil', 'British Indian Ocean Territory']]



ten_character = []

for sublist in countries:
    for ten in sublist:
        if len(ten) < 10:
            ten_character.append(ten)

            
print(ten_character)





That is it!