Posts

Showing posts from 2020

Introduction to webshare API (navigator.share)

Image
navigator.share is a JavaScript API providing a sharing interface similar to native apps
webshare API is supported on most updated mobile browsers Including Google chrome for Android
Sharing is done by passing an Object with parameters "url", "text" or "title" to navigator.share function.
For a webshare request to succeed you must supply at lest one of the parameters
navigator.share returns a Promise upon being called "upon
navigator.share({
    "url": document.location,
    "text": "I'm an example",
    "title": document.title
})
.then(resp => console.info("Successfully shared"))
.catch(errors => console.error(errors))

How to stop moz dotbot from accessing your website

Image
DotBot is Moz's web crawler, it gathers web data for the Moz Link Index
Dotbot obeys robots.txt rules before accessing your host machine so the easiest way to stop dotbot is by adding robots.txt rules that limit dotbot activities
To forbid a directory let's say "login" add;
User-agent: dotbot
Disallow: /login/
Upon reading and parsing directives above moz dotbot won't dare access you sites login sub directory in it's craw routine
To forbid an entire website's access include directives below;
User-agent: dotbot
Disallow: /
Alternatively you can limit crawl rate by adding directives below "time is probably in seconds"
User-agent: dotbot
Crawl-delay: 10
I've attached an nginx log it's a trail left by dotbot along with it's ip and moz support e-mail address;
216.244.66.194 - - [19/Mar/2020:15:16:29 +0000] "GET /index.html HTTP/1.1" 200 13433 "-" "Mozilla/5.0 (compatible; DotBot/1.1; http://www.opensiteexplorer.o…

How to set content disposition header for nginx server to force content download

Image
Nginx (pronounced as engine x) is an HTTP server, reverse proxy server, as well as a mail proxy server
Nginx is well known for its high performance, stability, efficiency, rich feature set, simple configuration, and low resource consumption.
content disposition headers direct web browsers to save content instead of attempting to render it
To set content disposition open your desired server configuration in "/etc/nginx/sites-available/"
within your configuration add code below within your server {block}

location ~* (mp3|ogg|wav)$ {     add_header Content-Disposition "attachment"; }
mp3, ogg and wav are example file extensions matched by regular expressions rules
Test configuration by acessing mp3, ogg and wav files from your webserver
Alternatively you can force custom filenames as shown below "$1" substitutes filenames sent to clients. As an example its value corresponds to the requested file's extension
location ~* (mp3|ogg|wav)$ {     add_header C…

Reasons why you shouldn't consider hosting on github pages

Image
Github pages is a service for deployment of static websites normally software documentation and blogs
Github pages is available on all public github repositories and on premium accounts it extends to private repositories as well.
So what's not to like about it. hmmmm think about it. that's too good to be true It's not a secret that "the only free cheese is served on a mouse trap"
1. "Downtime due to maintenance" Every now and then github pages websites undergo an annoying and imaginary maintenance that causes undesirable user experience especially for professional websites.
2. "Slow deployment"
I've been using github pages to host my static website with less than 10,000 pages deployment process knocked my entire site offline for 10 mins again that's unnecessary downtime sometimes it extended to days
3. "uninvited cloners"
So you put your site out there few days later 50 clones uninvited unwelcome and unnecessary
4. "Limi…

How to set content disposition headers for express nodejs apps

Image
In express nodejs apps you can force the user agent "browser" to rather download content instead of displaying or attempting to render given content within the browser.

In this example assuming you're using express.static to serve content pass an Object as second argument to express.static function

An Object with configuration parameters; const config = {
setHeaders: res => res.set('Content-disposition',  'attachment')
}

In your code replace "path/to/media/" with the path pointing to the static content.

app.use('/media/', express.static('path/to/media/', config))
To test try accessing content at /media/*

HTML minifier module for Nodejs

HTML minification is a process involving striping off unneeded, abundant or otherwise unused HTML attributes and elements without affecting the webpage appearance.minification is useful for statically genetated 'serverless' web application webpages as it delivers easy to digest minimal webpageshtml-minifier is free and open-source npm nodejs module written in JavaScript for minifying HTML documents, as compared to similar nodejs html minification modules html-minifier proves to be pretty fast, flexible and efficienthtml-minifier module can be used to minify HTML code programmatically or alternatively you can minify HTML code using global commandline moduleNpm module InstallationTo install module in your terminal typenpm i html-minifierTo install commandline version of html-minifier in your terminal type npm i -g html-minifierusage:
html-minifier [options] [files...]options:
--remove-comments
Strip HTML comments--remove-empty-attributes
Remove all attributes with whitespace-onl…

Open-graph meta data tags introdution

Open-graph elements are meta tags that contain extra meta data of a webpage open-graph is used by Facebook to create website cards for urls shared on it's platform  cards contain website image thumbnail and as well as title, description, type and url open-graph meta tags have a property attribute containing a property prefixed by "og:"For example;<meta property="og:image"  content="image-url">

Solutions to blocked URLs on Facebook

Facebook allows sharing links on it's platform but in order to protect it's users from accessing URLs containing malicious content Facebook on a regular scraps content on shared URLs effectively raising an alarm if content shared goes against Facebook community standards or in short it's content is forbidden on the Facebook platform,Forbidden content may include potentially malicious crafted phishing websites or websites spreading malware among othersFacebook may as well ban content flagged spam either reported or flagged by Facebook moderating algorithm "Facebook sheriff"You wouldn't want to find your website 'spam-list handed' you should avoid thatThere's no way to redeem a website flagged as a blocked website on Facebook except other non viable alternates such as completely changing your domain or using another sub-domainFacebook may as well ban content containing banned URLs in the meta open graph attributesTo resolve open-graph sharing relate…

How to remove null elements from array in JavaScript

Every now and then arrays normally tend to have null or otherwise empty elementsArray filter is a specialized JavaScript function for filtering array elements found to be matching a given criteria for example;const arr = ['max', 'duke']In order to remove duke from elements of the array you can do it as follows;arr.filter(name => (name == 'duke' ? false : true))// returns ['max']You can filter empty and false elements as well, using a similar syntax as done above;const arr = ['max', null, 'duke']arr.filter(name => name)
// ['max', 'duke']

How to strip out html using regular expression in JavaScript

Regular expression isn't a very viable solution for manipulating html due to the complexity of html syntax in the browser it's recommended to create dom elements, appending html source code and then manipulating it using built-in dom querySelectors that has few drawbacks especially for environments without a dom take for instance nodejsYou can use regular expression replace function as;const str = "<b>John swana</b>"str.replace(/(<([^>]+)>)/ig, "")// John swanaAnd that's it

Es6 new features summarized round up

Escmascript es2017 or better known as es16 is the edition after the famously popular es15, In this edition there are only two new additional features the exponention operator and Array.prototype.includes() functionexponention operator** Operator is a short hand method used for raising numbers to their powerIts syntax is similar to native operators such as '+' Addition and '-' (minus) for subtractionExample usage
Initially to raise a number to the power you would need to use math library pow function as;Math.pow({number}, {factor})Since es2017 you can simplify the operation above down to simply as;{number} ** {factor}Example as;5 ** 2
// Giving you 25Array.prototype.includes()Array includes is a feature similar to a pre existing function array.indexof() as compared to array.indexof() array.includes() function notably returns a true  boolean on matched value, and false if value not matchedExamples on how to use 'array.includes()' functionThe first argument is the…

unused css rules tree shaking elimination nodejs

Unused css rules elimination process is a lot more like tree shaking done by JavaScript bundlers for instance if you're familiar with how webpack eliminates dead code as a result tree shaking generates a much smaller bundle with only essential codePurifycss is a nodejs npm open source package that eliminates unused css
You can use purifycss to remove excess css from libraries such as bootstrap, materal design lite to name a few,InstallationYou can get "purify-css" npm package from the package manager by typing in your terminal;npm i purify-cssTo install globally add -g flag;npm i -g purify-cssBasic example usage;
You can use css purify global cli package as;Syntax;purifycss {css} {html}Important flags;-m minify output
-o specify output file nameFor example;purifycss *.css *.html -o css.min.cssOutput containg minified css rules will get saved to css.min.css

what is 'array.includes' function in JavaScript

Array includes is a feature introduced in JavaScript es16 or es2017 it's similar to a pre existing function array.indexof() as compared to array.indexof() array.includes() function notably returns a true  boolean on matched value, and false if value not matchedExamples on how to use 'array.includes()' functionThe first argument is the value to be looked upon in an array;const arr = ['dogs', 'cats', 'snakes']arr.includes('liars')
// falsearr.includes('snakes')
// truearr.includes('lizards')
// falseI hope you get the concept

'**' exponential operator in JavaScript

** Operator in an es6 Escmascript feature a short hand method used for raising numbers to their powerIts syntax is similar to native operators such as '+' Addition and '-' (minus) for subtractionExample ussage
Initially to raise a number to the power you would need to use math library pow function as;Math.pow({number}, {factor})Since es2017 you can simplify the operation above down to simply as;{number} ** {factor}Example as;5 ** 2
// Giving you 25

How to make a Snake Game using JavaScript and html5

Image
I compiled stapes to create a game similar to Nokia developed, popular game called 'snake'

Snake was first developed by Nokia, programmed in 1997 by Taneli Armanto and published on Nokia mobile devices,  It was introduced on Nokia model 6110, 3310 from 2000 and later the game was rebranded as "Snake Xenzia" Included on later mobile phone models

I made a version that is more simplified and more beginners friendly, It's based on the same idea of making a snake that grows as it eats stuff and the score increases as it grows

I'm implementing this whole game in pure vanilla JavaScript and a taste of html5 canvas, In this project the canvas is used as a renderer for the game's visual output

conceptsandinitialideas

I got the idea while doing another retro gaming project, i thought it would be good too if i created this game, from start my plan had been simplicity and making this game easy to implement, So to simplify everything i had a great deal of planning pr…

How to create zip archives in nodejs

I'm going to compile ways in which you can create archives compressed using zip algorithm in nodejs or a similar JavaScript runtime.node-zip is an open source zip archiving utility authord by daraosn and folked from jszip capable of compresding files into a zip archive and extracting zip archives in JavaScript.node-zip is available on npm you can install it in your terminal window by typing;npm install node-zip example usageconst  zip = new require('node-zip')()
zip.file('test.file', 'John Swana')const data = zip.generate({base64:false,compression:'DEFLATE'})
console.log(data)How to unzip a ziparchiveconst zip = new require('node-zip')(data, {base64: false, checkCRC32: true})
console.log(zip.files['test.file'])

Basic commands to open, zip and unzip archives

zip  is  a compression and file packaging utility for Linux, Unix OS, MAC and MS zip utility comes handy with another companion program called unzip, unzip is used to list, test and extract zip archivesBasicusage;zip basicusage;Zip command line program can be used to compress files as;zip -{flags} {package} {item}Example on how tozipafileusingzipYou can zip and compress a file as;zip pack.zip filename.mp3Zip will get the command to package filename.mp3 and store it in an archive named pack.zipHowtocompress a directorywith zipDirectories can be archived using the -r flagYou can zip and compress a directory as;zip -r bundle.zip directoryHowtounzipfilesusingunzipunzip a companion program to zip is used to extract archives typed unzip followed by archive name to extract a package as;unzip  {filename}for example;unzip pack.zip

Tar basic commands to store and extract files

Targeted is an archiving program designed to package, store, and compress multiple files into a single portable package the name tar is an abbreviation for tape archiverApart from creating .tar archives tar is also capable of compressing files using zip, bzip2, and gzip compression algorithmsTar flagsc — compress directive
x — extract directive
t — tabulate contents
f — specify filename
z — use zip/gzip compressionj — use bzip2 compression
k — do not overwrite
t — files from file
w — ask for configuration
v — verbosegzip flagsd — decompress fileTar commandline commands syntaxtar -{arguments} {params}Example tar commandstar -cf music.tar music.mp3Tar archiver will be directed to compress music.mp3 into a tar archive named music.tar and save it in the current working directorytar -xf music.tarTar will be directed to extract music.tar archive and save the constituent contents of the archive in the current working directoryhowtomake a zip archivesusingtarTar can compress zip files as well…

How to install tfjs JavaScript library

Image
Tensorflow is a hardware accelerated JavaScript library for building, training, testing and deploying machine learning models on a JavaScript runtime environment.
Installation through html script tag For use within the browser you can link to jsdelivr content delivery network using an html script tag as follows;
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js"></script>
Installation through npm package manager Alternatively you can install a self hosted version of tensorflow from npm, in your terminal type;
npm install '@tensorflow/tfjs'
Installation for tfjs-node on npm tensorflow has two nodejs packages made specifically for nodejs
Installation for '@tensorflow/tfjs-node' This version is a cpu only version it doesn't utilize gpu to do the computing, install tfjs node by typing;
npm install '@tensorflow/tfjs-node'
Installation for '@tensorflow/tfjs-node-gpu' This version is arguably faster than the …

String repeat in JavaScript

String repeat is a function that can be used to multiply a string for a given number of times, its a feature that is closely related to string multiplication operator in Python programming language, as compared to Python's syntax;
("String") * (number of times to repeat) "A" * 3
// returns "AAA"
Something similar may be archived using string repeat function in JavaScript as;
("String").repeat(number Of times to repeat)
For example to triple "A" you can do as;
"A".repeat(3)
Practical example is with lyrics;
const part = "i feel you, "
const lyrics = part.repeat(4) + " A, B, C" // "i feel you, i feel you, i feel you, i feel you, A, B, C"
Further reading;
String.prototype.repeat() MDN

Lambadas in kotlin programming language

Lambadas are similar to arrow functions in JavaScript they are a short alternative method to declare functions in kotlin programing language, You can create a function expression as;
val double = {num: Int -> num * 2} val cube = { num: Int -> num * num * num} val square = {num: Int ->
    val product = num * num
    product }
The last expression in a lambada is considered as a return value; Parameters can be omitted, for a single parameter lambada the value of the omitted parameter is in the variable 'it'

Rest operator in JavaScript

Rest operator is similar to spread operator its an es6 feature that allows converting arguments to an array of values;

Syntax of spread operator is as follows;

function spr(...params) { console.log(params) } spr(1,2,3) // [1, 2, 3] You can use rest operator among other arguments

function sprr(args, ...params) { console.log(params) } spr('foo', 1, 2, 3) // [1, 2, 3] More information:
Restparameters MDN

JavaScript String includes function

String includes is a function introduced to JavaScript in Escmascript 'es6' that returns a boolean true , or false based on the evaluation whether or not a string contains the string passed as an argument to the function For example;


const str = "John swana" str.includes('John') // true str.includes('duke') // false Running string includes testing whether 'John swana' includes John returns trues as it's a fact.

Running the same string against duke returns false duke is not part of the string 'str'

comparison on var, let and const variable declaration

Introduction
let, const and var are keywords used for variable declarations in JavaScript programming language,const and let were newly introduced to the programming language in Escmascript es6 or es2016.Declaration keywords
the syntax of declaring a variable using let keyword is done as;let {variable name} = valuefor const it's done as;const {variable name} = valuesimilarly with var;var {variable name} = valueScope for 'let' and 'const' variables
let and const declared variables are block scoped that means values assigned remain within the block of assignment;
take for instance;if(true) {
   const declaration = "declared"
}console.log(typeof declaration)
// undefinedvalues remain accessible only within the if blockScope for 'var' variables
var declared variables are function scoped so variables declared within a function are only accessible within the function it's self for example;function assign(param){
    var assignment = param;
}assign(&…

Es6 destructuring operator in JavaScript

JavaScript from es6 enables destructuring operation,
In JavaScript destructuring is done using the syntax;
const [elements] = [array] const {properties} = {object}
For instance using Math object as an example destructuring can be done as follows;
Object matching syntax;
const {abs, min, max} = Math;
List matching syntax;
const [max, min, avg] = [10, 1, 5]
Fail-soft destructuring similar to object property look up returns undefined if there's no property matching;
var [item] = [];
item === undefined;
Fail-soft destructuring can also be done with predefined default vslues as follows;
var [item = 1] = [];
item === 1;
More information: MDNDestructuringassignment

How to write a self invoked function in JavaScript

Self invoked functions are function that run on themselves without need to be called, the syntax to create self invoked functions is as follows;

(function(){ // function body })() the runtime will run everything in a self invoked function's body You can pass parameters to the function using the syntax below;
(function(params){     // function body })(params) parameters will be made available to the function as any other argument

JavaScript default parameters

Image
Since es6 its possible to include default function parameters just like other programing languages such as php do, default parameters cut down the need to initially set default Parameters within the code as;
const vec function (x, y){ if(typeof x == "undefined") x = 0; if(typeof y == "undefined") y = 0; return { x, y } }
now the above can be done in a more simple way , using default parameters as;
const vec function (x = 0, y = 0){ return { x, y } } In either of the functions if you omit either of the Parameters your parameter will default to zero ie 0;

How to get first and last character of a string using 'String.startsWith' and 'String.endsWith' in JavaScript

Image
String starts with is an emcscript es6 feature that allows JavaScript developers to test a string if the first character of a string matches the given criteria ,

Take for instance you have a string, you want to test if it starts with characters '#'
const str = "#JavaScript" cons strr = "I love #kotlin" str.startWith('#') // true strr.endsWith('#kotlin') // true strr.startWith('#') // false str.endsWith('#kotlin') // false Both functions return a boolean true for a match and false if there's no match.

endsWith does what startsWith does except that it does it at the end of the string

How to make a static http server in nodejs using express

Image
Express is a fast unopinionated, minimalist web framework for nodejs Authored by  TJ Holowaychuk
Express is a framework for building robust http servers, single page applications and API's among others.

How to create an http server in express

Open your text editor and terminal,
run the commands below to create a project directory, application file
and a landing page

mkdir project
cd project
mkdir static
echo "Hello World" > static index.html
touch app.js

You must have a directory structure as follows; |Project/
    |static/
        |index.html
    |app.js

Project directory is the root directory of the application Static directory is where static files, webpages will be stored.

index.html is an index page with text "Hello world".

app.js is a blank JavaScript file, open your editor and paste the following few lines of code into app.js


import express from 'express' const app = express() const port = 3000 app.use('/', express.static('static…

How to tabulate array key values using console.table

console.table is a function for tabulating arrays key value pairs it retuns a table when given an array as input. const table = Array(5).fill(0) console.table(table) ┌─────────┬────────┐ │ (index) │ Values │ ├─────────┼────────┤ │ 0 │ 0 │ │ 1 │ 0 │ │ 2 │ 0 │ │ 3 │ 0 │ │ 4 │ 0 │ └─────────┴────────┘

How to use 'console.assert' for assertion in JavaScript

console.assert prints text passed as second argument if the first argument returns false;
for example,


const notTrue = false; console. assert(notTrue, 'I\'ts false') // return "it's false" You can use console.assert to perform simple unit tests of your JavaScript application.

const application = function(params){ if(params.num < 10) return false else return true } const instance = new application({ num: 5 }) console.assert(instance, 'number less than ten') // return "number less than ten"

What is strict mode in JavaScript

Strict mode is a ECMAScript 5.1 feature used mainly for testing and debugging. when enabled the JavaScript engine catches more errors among others undeclared variables, duplicate object properties. How to enable strict mode,
In your code include; 'use strict'; You can put the declarative on the top most line anything that comes after it will be handled in a strict manner.

How to change a String's Case in JavaScript

Image
Strings can be capitalized using String.toUpperCase
For instance;
const str = 'John swana' str.toUpperCase() // 'JOHN SWANA' String.toLowerCase turns strings to their small letters or 'lowerCase'

const strr = "Lorem ipsum" strr.toLowerCase() // lorem ipsum Numbers are not converted, they remain constant, untouched and unchanged.


'65'.toLowerCase() // '65'

Array concat method in JavaScript

Image
Array concat is a method and an array property for concating one array onto another to archive merging of array elements.
Syntax for array concat;
const arr = [0,1,2,3]
const arrr = [4,5]
arr.concat(arrr) // [0,1,2,3,4,5]
Merging nested arrays using spread operator. It's possible to merge nested arrays to form a uniform array.
Take for instance you have two 2-dimensional arrays,
Or let's call them matrices
const arr2d = [[1,0],[0,1]]
//[[1,0],
// [0,1]] const arrr2d = [[1,1],[0,1]]
//[[1,1],
// [0,1]]
For instance you want to reduce the two 2-dimentional arrays and create a new array instance;
[].concat(...arr2d.concat(...arrr2d)) // [1, 0, 0, 1, 1, 1, 0, 1]

How to interpolate strings in Kotlin programming language

Image
Kotlin programming language has string interpolation similar to template literals in JavaScript
For JavaScript You can write as;
var passage = `I'm going todo a ${chore}`
In Kotlin you can do string interpolation as;
var passage = "I'm going todo a $chore"
Interpolating expressions in kotlin is done as;
var state = "I'm done with ${numChores()} chores"

How to get user's ip address in JavaScript

An IP address is a unique numerical label given to a computer when connected to a network;ipify.org is a free service that retrieves IP addresses in JSON formatfetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(response => console.log(JSON.stringify(response)))// response
{"ip":"--.---.---.---"}
In nodejs you can use a package node-fetchInstall it by typing;npm i node-fetchOr using curl, in your terminal type;curl 'https://api6.ipify.org?format=json'// response
{"ip":"--.---.---.---"}

How to install git on a raspberry PI

Image
Its impossible to write software without using Git, Git according to Wikipedia is a distributed version-control system for tracking changes in source code during software development.
A Raspberry PI is a credit card sized single board computer usually running a linux operating system "Debian, or raspbian" preferably used mostly by schools to teach students computer basics.
How to install apt on a raspberry pi;
Install using apt package manager,
To install using apt open your terminal type;
sudo apt update
sudo apt upgrade
sudo apt install git
You will be presented by a apt screen with package information confirm by pressing y followed by Enter;
Once installation completes you can check if the installation was successful by typing;
git --version
Upon successful installation you will be presented with git version number such as;
git version (2.11...)
Next step is to configure git, before doing any cloning you will be required to configure Git by adding your email address.

How to evaluate a string on a regular expression rule in JavaScript

JavaScript has a built in regular expression function for testing if a string arguments is matching the given regular expression rule;Syntax of the regular expression tester is as follows;/regex/.test(string)Take for instance you want to test if a string contains only alphanumeric upper and lower case characters, space and numbers;const str = "Eat code sleep"/[A-Z,a-z,0-9, ]*/.test(str)
// returns boolean 'true'Or in another example;const str = "Eat, Code, Sleep"/[A-Z,a-z,0-9, ]*/.test(str)
// returns boolean 'false'Because commas are not included in the regular expression match rules.

What is 'this.' keyword in JavaScript

In JavaScript 'this' is an object and a reference to the current object that is used to get and to set properties of the current object.Take for instance within a function;const func = function (name){
    this.name = name
}func.name instance property name is set to that of the first argument;const inst = new func('duke')inst.name
// returns dukeYou can as well extend func to set name using 'this';func.prototype.set = function(name){
    this.name = name
}Running the previous instance with this set method;inst.set('John')
// returns John

How to create promises in JavaScript

Promises enable asynchronous programming, JavaScript is single threaded,
You can use them to wait a lengthy promises take for instance an ajax or fetch process then once ready process the response.How do declare an asynchronous function,
To declare an asynchronous function add async keyword befor function name;const func = async function() {
    return 'OK'
}function func will now return a promise;const inst = func()
.then(response => console. Log(response))
.catch(err => {
    throw new Error(err)
}You can also await it like ummm;const response = await func()
console.log(response)Rejecting and resolution of promises,
This is done to distinguish successful promises from failed promisesconst statusReport = function() {
    return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), 10000)
   })
}You can inquire statusReport as follows;const analysis = new statusReport()
.then(() => console.log('hooray'), () => console.log('failure'…

How to use fetch api submit an html form

Fetch api allows asynchronous means of reading files and a more simplified way of making http requests in JavaScript.How to submit an existing html form using fetch api;Assuming you have html source code with a form and some input fields;<form id="form" action="./submit" method="post"
onsubmit="handle(event)">
<input name="query">
<button>
    submit
</button>
</form>You can pass an instance of a dom form to formData constructor as the first parameter;const handle = function(event) {
    event.preventDefault()
    const data = new formData(event.target)fetch('//localhost/api/post', {
    method: 'POST',
    body: data
})
}Fetch api returns a new pending promise to process the response you will need to await asynchronous process once ready to consume parse it as follows;.then(response => response.json()).then(response => console.log(response))

Constructor functions in JavaScript

A constructor function is a function whose instance is created using the 'new' keyword.Constructor functions in JavaScript can be declared using classes or by using JavaScript functions 'with few tweaks'HowtocreateaconstructorinJavaScriptFor JavaScript functions construction declaration can be made as follows;const greeting = function(name) {
    this.name = name
}greeting.morning = function() {
    const name = this.name
    return `morning ${name}`
}In the code bove declared a function greeting with a parameter named 'name'I further created a method named morning it returns a template greeting messageOnce the program gets run on a JavaScript engine the expected output is;morning + 'name provided'For instance;const greet = new greeting('John')greet.morning()
// returns 'morning John'Similar to using functions as constructors you can as well declare using classes;const greeting = class {
    constructor(name) {
        this.name = name
 …

What is /usr/bin directory on a linux, unix operating system

user binary directory or /usr/bin Is used to store user executable applications./usr/bin is also used as a look up directory by the shell so when you type a command the operating system will fetch /usr/bin for matching binary filesAs compared to /bin and /sbin , /usr/bin is a common  directory used to store user installed application files let's say text editors or webservers.

What is /sbin on a linux, unix operating system

What's the sbin directory on a Linux computer system ,An /sbin directory is a sub directory of root directory, sbin is an abbreviation of system bin.It's used used by the operating system to store and lookup essential system specific binary programs
ie ip, mkfs.*

How to build a twitter retweet bot using JavaScript

I'm sharing the code of my tweeter bot called 'JavaScript bot' I forked the original source code from a certain github repository written in nodejs the bot retweets a giver hashTag at a specified time intervalYou can use a twitter bot to promote an interest or a campaign unlike Facebook twitter is more tolerant on automated accountsI used to build Facebook automated accounts which were posting user friendly comments on my Facebook friends posts with no success few months down the line Facebook suspended my account until then i decided to stop using Facebook at allAnd twitter is just the right platform for this kind of thing.For this bot to work you'll simply need an APIs key and a secretTwitter doesn't need waiting the long verification process as of 2020 I created my developer account and almost instantaneously my account got approved.The twitter hard limit on the number of retweets per day is 1000;clone git repository using the command;git clone https://github.co…

How to wait for a promise within a loop block

JavaScript promises enable developers to write asynchronous applications in JavaScriptLoops are ways of iterating elements
For instance doing an asynchronous task within a for loop can be done as follows;
Note that lag is used to emulate some delay.const items = [1, 2, 3, 4]
const lag = async (delay) => {
    return new Promise((resolve) =>
        setTimeout(() => res(`${delay / 1000} sec`), delay))
}items.forEach(async (item) => {
    const seconds = await lag(1000 * item)
    console.log(seconds)
})expected output1 sec
2 sec
3 sec
4 secAfter running the code above every second some text was printed

What is a bin directory

A bin is an abbreviation of binary, a bin directory is a standard directory used to store executable binary applications.For example When you type a command on your terminal the operating system looks up for an entry in the bin directory
Take for instance.cowsay 'hello world'If you type out the command above your operating system will look up for a file named cowsay inside the configured bin directorylet's say /usr/bin/Should it find a relevant entry that matches the command 'cowsay' it will then pass arguments passed as parameters made available to the program 'cowsay'

How to pretty print JSON.stringify output

JSON.stringify is a method of JSON global which converts valid JSON to a serialized stringJSON is an abbreviation of 'JavaScript Object Notation' it's an independent data type that is not specific to JavaScript programming language.JSON is a global object with methods for manipulating JSON dataJSON.stringify is a method that converts JSON to a string its may be used for debug or simply to serialize JSONIt accepts three arguments (JSON, FUNCTION, SPACER)JSON: maybe an array or objectFUNCTION: Is an influencer it's a middle man that alters what is to be returnedSPACER; Is a character used to indent or prettyfiy outputFor instance take a look;const name = 'John'
const surname = 'swana'
const me = {name, surname}JSON.stringify(me, null, '    ')Returns the following output;{
    'name': 'John',
    'surname': 'swana'
}

Object assign in JavaScript

Object assign in JavaScriptObject assign is a static method of JavaScript Object global.Object assign is mainly used for merging two or more objects, where keys match Object assign overwrites one value of an object with the corresponding value of the same key in the second object.Example usage of object assign;const max = {
    name: 'max',
  type: 'dog',
    bread: 'fluffy'
}Given a situation where you want to derive a new pet of a certain name you will not need to redefine the whole pet structure instead just add or replaced the characteristics of the pet to that of your desire;const khloe = Object.assign(max, {
  name: 'khloe'
  type: 'cat',
  color: 'blue'
})// output after running the code above on a JavaScript engine;{
    "name": "khloe",
    "type": "kitty",
    "bread": "fluffy",
    "color": "blue"
}You can notice that Object khloe is a clone of ma…

What is a /home directory on linux, unix operating system

Home directory on a Unix or Linux operating system is root sub directory and a standard directory where the operating system stores user home directories under their own usernames/home/username/
/home/john/An individual's home directory is a space where one would store their personal items such as media files among othersAccess permission is dependant on the name and type of distribution of the operating system
751 perhaps :|How to go to your home directoryAmong Linux distributions they are a vast number of way one can get back home.On a standard Linux operating system directory path is stored in the $HOME variablecd    --- works
cd ~ -- works
cd ~/ --- works
cd $HOME --- works

E2020 dynamic imports in JavaScript

Escmascript Is a standard from which JavaScript and typescript are both derived from.ES2020 is out it comes with it new ways of writing JavaScript code.Dynamic imports enable importing dependencies in a rather dynamic way.Initially JavaScript developers were restricted to statically load their dependencies for instance;import { property } from 'dependency'On runtime the JavaScript engine loads the required dependencies and makes them accessible globally.However that is a rigid way of writing code.Dynamic imports are  relatively more flexible therefore you can included them at any segment within your program.For instance if you want to load file system module only if a certain criteria is met you would do as follows;If(process.argv[2] == 'start')
Import fs from 'fs'Dynamic imports return a promise use the syntax below to make use of themimport('fs')
.then(fs => {
   // consume module fs
})

Ways of iterating Object properties in JavaScript

For Objects the ways of iterating their properties are not that plentiful as with Arrays.take for instance we have an object of dogs and cat characteristicsconst pets = {
{name: "Jenny", eyes: "brown"},
{name: "max", eyes: "blue"}
}To iterate through the characteristics using for loopfor (pet in pets) {
    console.log(`${pets[pet].name} has eye color ${pets[pet].eyes}`}
}Alternatively you can use objects.keys and object.entriesfor (element in Object.entries(elements)) }

Handy array functions every developer should know JavaScript

Array make a good means of data storage and manipulation in JavaScriptif used well arrays are way better than objects especially if you're working with numbersArray.push(element)
Its a method used for quickly appending an element to an array
For instance
const arr = ['code']
arr.push('eat')
// ['eat', 'code']Array.unshift(element)
It's a method that's pretty similar to array.push except that unshift prepends an element to the end of the array
For instance
const arr = ['eat', 'code']
arr.unshift('sleep')
// ['eat', 'code', 'sleep']Array.shift()
Array.shift is a function that removes the first element of an array and returns it
For instance
const arr = ['eat', 'code']
const err = arr.shift()
arr returns
// ['sleep']
err returns
// eatArray.pop()
Is a method an array property similar to shift that removes the last element of an array and returns it. Array.pop() and array.sh…

Hello world application in Kotlin

Kotlin Hello World Application To get started open your editor and type the snippet of code below fun main() {
    println("Hello, World!")
}in kotlin main is the entry point function of an applicationfun keyword is used for declaring functions it acts like function does in JavaScript.Compile your application into jar
kotlinc hello.kt -include-runtime -d hello.jarExecute your application
java -jar hello.jarIf everything went well you should see "Hello World" output from your terminal

How to install Kotlin programming language

Kotlin is a programming language that is statically typed runs on the JVM and can compile to JavaScriptTo install kotlin using the Software Development Kit on Debian Ubuntu or Linux environment.First install the SDK using
Command:wget -O sdk.install.sh "https://get.sdkman.io"
bash sdk.install.shTo install kotlin Type the command:source ~/.sdkman/bin/sdkman-init.sh
sdk install kotlinTo install Java development kit (JDK) a vital dependency used for execution and compilation of kotlin code.
Type the command:sudo apt-get install openjdk-8-jre-headlessTo confirm installation type the command:kotlin -versionIt should return output similar to one belowKotlin version 1.3.61-release-180 (JRE 1.8...)

Introduction to Kotlin programing language

Kotlin is an open source statically typed programming language named after an island just like Java was named after an Indonesian island.Kotlin runs on the JVM and can compile to JavaScript.Uses for kotlin programming languageKotlin is a preferred programming language for Android application development second after Java programming language.Kotlin can be used for artificial intelligence and data science research applications.Because of its speed kotlin is a well suited programing language for web server application development.On rare occasions you can use kotlin to develop client side application simply because it can compile to JavaScript.Hello world application in kotlin programming languageKotlin applications must have a main method.
println is used for text output just like in Javafun main() {
    println("hello world")
}After compiling the output should be "hello world"Basic syntax variable declaration
Variables are declared using
'var' for mutable …

Get current url port, hostname and path in JavaScript

window.location is an Object with properties of current location namely window.location.href returns the href url of the current pagewindow.location.hostname returns the domain namewindow.location.pathname returns the pathname segment of the urlwindow.location.protocol returns the web protocol of the urlwindow.location.assign() loads a new document

Redirecting a webpage in JavaScript

Redirects are way of navigating a user to another webpage or location redirects are normally done by server side implementations.it's possible to do redirects using JavaScript too window.location is a object that stores current location information such as path, port, hostname and href or the location in the address bar of your browser changing it invokes a redirect it's a simple way to redirect a user to another webpageSyntax
window.location.asign('https://example.com')or simply likewindow.location = "https://example.com"or simply omit windowlocation = "https://example.com"

How to target all elements of a given class name in JavaScript

JavaScript getByClassName only targets one element by default Workarounds "loops"
Loops can mess up your code I personally don't like them.
To target all elements you will have to iterate through all of them for each element you will have to add a event listenerExample
For instance the are 3 links of a same class and you want to add event listeners on all of them
....
....
....
// JavaScript
const links = document.getByClassName("links")
for(var i = 0; i < links.length; i++)
links[i].addEventListener('click', event => console.log(event.target.get attribute('class')))

JavaScript event prevent default

JavaScript event preventdefault is a method for intervening event actions preventing normal events behaviorTake for instance you have an anchor on a page when a user clicks on it the browser by default navigates to a url in it's href attributepreventdefault syntax/// HTML
<a href="/" id="home">
    home
</a>/// JavaScript
home.addEventListener('click', function(event){
    event.preventdefault()
    // rest of
    // the code
})

With statement in JavaScript

JavaScript 'with statement' is a simplified way to access object properties as variables.Take for instance;const dog = "puppy"
const mascots = {
    'tux': "tuxedo",
    'cow': 'cow'
}with(mascots) {
    console.log(tux)
    // tuxedo
    console.log(cow)
    // cow
    console.log(dog)
    // puppy
}properties of mascots are converted to variables accessible within the with block 'dog' is not part of mascots and as a fallback, dog global is returned.At the time of writing this post with statement is discouraged.It's not allowed in 'safe mode'With the above sample you can do the same thing using destructureing operatorconst {cow, dog, tux} = mascotsconsole.log(tux)
// tuxedo
console.log(cow)
// cow
console.log(dog)
// puppy

Ways to iterate array items in JavaScript

A few days ago i introduced arrays and described what they are and how their elements can be iterated in JavaScript using 'for loop'There many other ways to iterate arrays namely Array.forEach, Array.map,
var array = ['eat', 'code', 'sleep']Using forEach
array.forEach(function(value, index){
    console.log(index + ': '+ value)
})// result expected
// 0: "eat"
// 1: "code"
// 2: "sleep"Using Array.map
array.map(function(value, index){
    console.log(index + ': '+ value)
})// result expected
// 0: "eat"
// 1: "code"
// 2: "sleep"It's a wrapp

Lexer and tokenizer for robots.txt in JavaScript

Introduction I'm sharing how i made lexer and tokenizer for robots.txt in JavaScript

Reasons and motives I'm using it in the Nodejs environment of course so it's server side it's part of another project I'm doing.

How it's done robots.txt files contain one directive per line inform of

Key: value
Take for instance

User-agent: Googlebot/{version}
Disallow: {path}

Path the disallowed location it may included wildcards ie "*" or "/" its not a good idea to consume them raw without validation

And version number is ignored to make targeting bots easy i guess
Steps taken by the lexer
Splitting text into an array containing data from the robots.txt file line by line given it's provided with an input looking like this

User-agent: Googlebot/{version}
Disallow: {path}

It may return something that's like this [User-agent: Googlebot/{version},
Disallow: {path}]

Almost there. after that next step is to remove comments from each line using regEx

Af…

Removing bash.sh #hash comments from a string using regEx in JavaScript

Last night i was looking for a method to remove comments from a robots.txt file containing contents of form below`# robots.txt
user-agent
Disallow:`Or a more practical format obtained by splitting the robots.txt file line by line.["# robots.txt",
"user-agent",
"Disallow:"]every element of the array is a string representing a single line of text from a robots.txt plain text file.Regular expression
I used regular expression to strip out the unwanted text until the end of the line
however it's not limited to robots.txt it works perfectly with bash.sh files as well.Example
var string = "Disallow / #deny bots"
string.replace(/#.*$/, "")
// returns  Disallow /It simply strip's off all characters after the hash character until the end of the line.

How to iterate array elements using 'for loop' in JavaScript

JavaScript arrays are similar to arrays in c and in c like programming languages such as php among others In JavaScript arrays are simply collections of elements for instance Objects Numbers or other ArraysDeclaring an array
An array may be declared using the array constructor for instanceconst array = new Array()
or as
const array = []Iterating an array using 'for' loop
This is the implest and most common method to iterate an array is by using the 'for loop' am sure you're familiar with the syntax. take for Instance you want to iterate an array of integers and print each one of them.var ints = [1, 2, 3, 4]To iterate ints using for loop.for (var i = 0; i < ints.length; i++){
        console.log(ints[i])
}// output will be
// 1
// 2
// 3
// 4In between the parentheses they are three procedures in three segments separated by colonsfirst segment declares var i an index which gets incriminated in the third segment as long as it's less than the length of the ints…

How to use canvas context rect method for drawing rectangles

canvas context rect method does as it says. It's used for drawing a rectangle on a canvas contextParameters
context.rect(positionX, positionY,
Width, Height)PositionXspecifies the x coordinate at which the rectangle should be drawn at on the contextPositionY specifies the y coordinate at which the rectangle should be drawn at on the contextWidthspecifies the width of the rectangleHeightspecifies the height of the rectangleStroking and filling the rectangle
In order for the rectangle to be actually visible you have to either stroke it or fill it with a color.Stroke
Stroking a rectangle means to draw a line that joins all of it's vertices
To specify the fill color you should set it and call stroke to draw
context.strokeStyle = "#colors"
context.stroke()Fill
Similar to srokings filling a rectangle means to paint it's inner bounding box with a specified color
context.fillStyle = "#colors"
context.fill()Example
context.rect(0, 0, 100, 100)
context.strokeSty…

Install steam locomotive sl using apt

sl or steam locomotive is a commandline application that displays steam locomotive "train" animations aimed to correct users who accidentally enter sl instead of ls.  initialssl stands for Steam LocomotiveHowtoinstalllsorsteam locomotiveAssuming you've root privileges and installed apt package manager on your system
Typesudo apt-get update
sudo apt-get upgrade
sudo apt-get install slTo test installation type
sl
If installation was successful You'll see an ASCII image of a train right in your terminal after few seconds it will stop

JavaScript canvas introduction

Introduction
Probably next monday I will post a how to make a snake game clone in a few lines of JavaScript code post don't miss it out subscribe to my email newsletter!What isa canvas
I'm sure you've heard of the term somewhere. canvas through their "2d" context allow drawing 2d graphics using a simple JavaScript apiYou can use a canvas to draw text , lines simple shapes, and images
canvas can also be used as a renderer for JavaScript built html5 games "that's were we're going"Example on canvas
it draws a rectangle on a canvas context black color by default<html>
<canvas id="canvas"></canvas>
<script type="text/javascript">
        var context = canvas.getContext("2d")
// stroke a 100px square at 0, 0
context.rect(0, 0, 100, 100)
context.stroke()
</script>
</html>Save and open it in your browser you should see a square on the top right corner of your browse window

JavaScript spread operator

JavaScript spread operator is a useful operator for manipulation of objects , strings and arrays in JavaScript among others you can you it to effectively copy an object or array expand it or even convert a string into an array of its constituent characters.const chars = ["a", "b", "c"]
const name = "John swana"Copying an array using spread operator
to copy an array using a spread operator you can do it using the syntax as followsvar alphabet = [...chars]
And now alphabet contains chars properties
alphabet // ["a", "b", "c"]Copyinganobjectusingspreadoperator
Similarly you can copy JavaScript objects using spread operator. Take for instance
const object = {name:  "John swana", gender: "male"}
var user = {...object}
user //  {name:  "John swana", gender: "male"}Convertingastringintoanarray
Note that you can use String.prototype.split for this operation if you want
var array = [..…

Installing and using 'cowsay' with fortune

what is 'cowsay' it's a simple commandline program of a cow which basically prints whatever text argument you pass to it inform of a speech bubble from a ancii cow
c:owsay goes hand in hand with another cli programme called fortune it generates text fortune messages which can be easy be tunnelled into cowsay
Cowsay is so popular that i decides to write a how to installation post
To get started open your commandline terminal and type sudo apt-get update 
sudo apt-get upgrade
sudo apt-get install cowsay
To install another cli app 'fortune'
type the following in your terminal
sudo apt-get install fortune
After installation test fortune by typing in your console fortune // typical response Training is everything.  The peach was once a bitter almond; cauliflower is
nothing but cabbage with a college education.
                -- Mark Twain, "Pudd'nhead Wilson's Calendar"
To test cowsay type cowsay followed by a command you want to be said 
Cowsay will print a cow in yo…

JavaScript class getters and setters

Introduction
I assume you know heard or at least in someone's code seen JavaScript classes. newly introduced classes are much better than functions if your code requires inheritance of constructors "classes"Brief subintroduction
A class can be made using syntax below given cats as an exampleclass chat {
    constructor(params) {
        this.name = params.name
        this.color = params.color
    }
    meow() {
        console.log("meow meows" + this. name)
    }
}Explanation
cat is a class with a constructor and a method named meow note that you can omit the constructor in the above code if you have nothing to initializeAdding Getters
getters are a piece of code that retrieve properties of a class in class cat they're no user defined getters
JavaScript properties can be retrieved even if you don't use getters for instancevar kitty = new cat({
    name: "tom",
    color: "black"
})kitty is now an object to retrieve kitty properties …

JavaScript es6 modules import, export

Java scrips modules are libraries that export importable properties.With modules you can create reusable independent separate components es6 modules should provide one or more exports.exports can be ie a function or an object take for instance you created a math library you can use the syntax below to create a module.// saved as lib-math.js
export function cube(num) {
    return num * num * num
}To make use of lib-math above in a simple calculator function you can import it as// saved as calculator.js
Import {cube} from "./lib-math"
function calculator(num) {
    return cube(num)
}// calculator(5) // returns 125
// calculator(3) // returns 27
// calculator(2) // returns 8Alternative ways to export
You can export a function as in the example above or you can export functions as an object assuming you have more than oneexport {cube, sqrt, .....}Ways to import a module importing modes is done by the follow keyword following by from proceeded by the relative path or module name …

JavaScript es6 template literals

Template literals are a new syntax to create strings in JavaScript Embedding expressions in a string is now possible using template literals thus there's a new way to embed expressions into strings effectively interpolating the values done using syntax ${expression}
within a string for instanceconst text = 'Hello world'
const string = `Say ${text}` // Say hello world.You're not only limited to that you can as well perform more advanced expressions and arithmetics as wellconst string = `${1 + 2}` // returns 3stringsthatspawnmorethanonelineare now possible with template literals initially the only way to create strings that spawn multiple lines was to break it up in parts the syntax below is now possibleconst text = `
loading....
processing...`

JavaScript var const and let

Signification and let are new JavaScript methods of declaring a variables on modern browser's you don't need to enable strict mode to make use of const, and letWhat'sthedifferencebetweenvar , letandconst
Immutability when you declare a variable using const its value is immutable ie you can't simply reassign the variable with another value neither can you declare const variables as
const variable, another;
because it's pointless afterallscope of this
let variable decelerations are block scoped therefore if used in an if statement or in a function its value is scoped within that block

Arrow functions in JavaScript

Since their introduction arrow function have simplified how we declare functions in JavaScript arrow functions are similar to lambadas in kotlin programming language
Instead of writing a function as function time (param){
    return Date.now()
} You can simplify code by rewriting it as simply let time (param) =>  {
    return Date.now()
} Alternatively you can use a neatier syntax let time = param => Date.now() Arrow functions this context does not refer to their scope.
For further reading "learn es6 the dope way part ii arrow functions and the this keyword", https://medium.com/@__Masha__/learn-es6-the-dope-way-part-ii-arrow-functions-and-the-this-keyword-381ac7a32881