Separating WSL (Linux) path and Window path

I often find myself hacking the Linux kernel for fun and profit. This time I was trying out Buildroot Embedded Linux build system and the first stumbling block using WSL was the fact that Windows path containing spaces were appended to the WSL path which the Linux file system has issues with. Running make for the Buildroot gives the error below:

Your PATH contains spaces, TABs, and/or newline (\n) characters

Follow the steps below for the solution:

  1. Create a config file for WSL interop in the WSL distro you are using. sudo nano /etc/wsl.conf
  2. Copy and paste the config below in the file:
[interop]
appendWindowsPath=false
  1. Save then restart the WSL distro in the Windows shell (not the WSL distro).
wsl -d [distribution name] --shutdown
wsl -d [distribution name]
  1. Check the path to echo $PATH to ensure all is well, only the Linux path should remain.
  2. And we are done! Finally we can build our kernel without worries.

If you forget your Windows Subsystem for Linux (WSL) password, try this.

I have been using Windows Subsystem for Linux (WSL) for a while now and sometimes I create a distribution and forget the password. If you find your self in the same situation, just follow these steps:

  1. Open the Windows Shell.
  2. Type in wsl -l to get the list of WSL Distributions you have on your system.
  3. Login to the distribution using wsl -d [Distribution Name].
  4. Type in whoami to get your default user name. Note this down.
  5. Logout of the distribution, by typing exit.
  6. Log in as root: wsl -d [Distribution Name] -u root.
  7. Change the password for the user by running this passwd [User Name] and follow the instructions.
  8. If all goes well you should get a “passwd: password updated successfully” message.
  9. Logout again using exit .
  10. Now you can use the new password for your WSL Distribution default user.

Hope this was helpful to you. Thanks for reading.

System statistics reporting using Laravel

The Laravel web framework comes with a lot of powerful tools and one of them it the Task Scheduler. This allows you to create and manage all your automated – Cron Jobs – tasks within the framework. If you do not write Cron jobs often, going through documentation or memorizing the Crontab syntax and expression can be extra work (I usually use crontab.guru to simplify this ). Laravel uses functions such as everyTwoMinutes() which is simple to remember and implement. There is also per second scheduling which is not available by default on crontab.

First, you have to open the app/Console/Kernel.php file. Your scheduled task will be added in the schedule(Schedule $schedule) function, by calling the $schedule object. There four main types of calls you can make using the $schedule object:

  1. A closure function containing Laravel/PHP code you wish to run.
  2. A command which runs an Artisan command.
  3. A queued Job.
  4. Command line scripts which can run external scripts.

I will be running an external script (using exec ) to get my systems stats and then send them to myself every 5 minutes. To use an already setup docker environment you can clone this repo and follow the setup instructions (If you choose to use the docker environment. Run your commands in the ‘web’ container) . Copy the code block below in the schedule function:

 
$command = 'echo "------------------" >> out.txt &&';
        $command .= 'top -b -n 1 >> out.txt &&';
        $command .= 'echo "------------------" >> out.txt &&';
        $command .= 'cat /proc/meminfo >> out.txt &&';
        $command .= 'echo "------------------"';
        
        $schedule->exec($command)
        ->appendOutputTo('out.txt')
            ->name('System Stats')
            ->everyFiveMinutes()
            ->emailOutputTo('me@example.com');

Then first test using php artisan schedule:test select the number associated with this task and click enter. if there are no errors, run php artisan schedule:work to start the scheduler if you are on a development environment. For production, add this to your Crontab :

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

NOTE:

  1. Ensure email sender (mailer) of choice is configured on the .env file.
  2. If you choose to use the docker environment. Run your commands in the ‘web’ container.

That’s it, you can include other server stats you want to send through email in the exec function of the scheduler.

References:

  1. Laravel Documentation: https://laravel.com/docs/10.x/scheduling#task-output

Improving systems performance with checksums: Part 1

Checksums are blocks of data generated from another block of data you want to store or transfer to ensure that correct data is transmitted during the process of moving data around. This is useful for data correction and security purposes. For example you could use a checksum algorithm to check if the data you download is the correct one ensuring that you do not download malicious data. Checksums can be implemented using hashes, cryptography, randomization, parity bits etc. 

Another application of checksum if validating data before submitting them to the database. An example of this is when you try to submit your credit card details and any error is flagged before submission to the database. A checksum algorithm checks the validity and correctness of the credit card number you are entering, this prevent the application from having to do a search for incorrect numbers therefore reducing the load the system has to bear.

A checksum algorithm that stood out for me is Luhn’s Algorithm, and I will be making a PHP implementation of it below:

<?php
// Script to check if a number is valid using Luhn's Algorithm

$cardnumber = "4890486808";

$sum = 0;
$numlength = strlen($cardnumber);
$parity = $numlength%2 ;
for($i=0;$i<$numlength-1;$i++){
    if($i%2 != $parity)
        $sum=$sum + $cardnumber[$i];
    elseif ($cardnumber[$i] > 4)
        $sum=$sum+ 2*$cardnumber[$i] -9;
    else
        $sum=$sum+ 2*$cardnumber[$i];
}
echo (10 - ($sum % 10))." is the checksum digit \n";
echo $cardnumber[$numlength-1] == (10 - ($sum % 10)) ? "Correct Number":"Incorrect Number" ;


?>

In the second part, I will be testing this algorithm with a database on Docker and comparing it with an application without a checksum.

Formula for converting IP address to long

After looking at PHP’s ip2long function I was curious about how this conversion is done. It is quiet simple and to achieve this conversion you have to take the IP address to be in base 256. Then add the product of the base raised to the power of the number position (0, 1, 2 & 3 ) and the value of the number in that position ( 1,0,0 & 127) as illustrated.

Below is a JavaScript code to calculate the long value of an IP.

let ip = "120.8.4.3";
let array = ip.split('.');
let int_array = array.map((num)=> Number(num));

let long_val = int_array[0]*(256**3) + int_array[1]*(256**2)+ int_array[2]*(256**1) + int_array[3]*(256**0)

console.log(long_val);

Have fun!

Setting up Raspberry Pi Zero W without a monitor, mouse or keyboard :

Setting up a Raspberry Pi Zero W board is quiet simple. All you need are:

  1. A Raspberry Pi Zero W board
  2. MicroSD Card Reader
  3. SD Card with a minimum of 8GB memory size
  4. A power supply for the board ( a USB cord will do if you do not have a power supply)

The items listed above are illustrated from left to right in the image below:

You will also need a computer ( I am running mine on a Windows operating system). Now that we are ready, The steps to follow are:

  1. We plug in our micro SD card reader with our microSD inserted into our computer and wait for it to show up on computer.
  2. We get the “Raspberry Pi Imager” on the Raspberry Pi website. Check out this link. This app will help us with installing and setting up our operating system for the Raspberry Pi Board on the microSD card.
  3. After installing the “Raspberry Pi Imager”. Run it, you should get the window below. Click on the button in the blue circle.
  1. You will get a window to select the operation system you want to install. Select the “Raspberry Pi OS (32-bit)”. This option gives us a Desktop we will be connecting to later in this tutorial.
  1. After selecting your OS of choice, you are taken back to the home screen where you choose the storage device – in this case the MicroSD card you inserted. CAUTION: Ensure the storage you selected is the microSD card you want to use for your Raspberry Pi board.
  1. Before you click ‘write’. Select the Gear icon button at the lower right corner of the window. This is the ‘advanced options’ and this is where you setup the board to connect your network on boot and setup login credentials. Do the following:
    • Enable ‘Set hostname’ and enter a name of your choosing.
      • Enable SSH, select use ‘password authentication’
      • Enable ‘Set username and password’. Enter values of your choosing. Don’t forget both, note them down, you need them to login.
      • Enable ‘Configure wireless LAN’. Enter ‘SSID’ which is the name of the WIFI network you want to connect to. Enter the WIFI password. Select ‘Wireless LAN country’ from the dropdown.
      • Click Save
  1. Click Write then wait for the app to download and install the OS with the option you added.
  1. After the installation process. Connect the board to the power supply and wait for it to boot – the green LED indicates the board is booting . Then check your network to ensure you can find a device with the hostname you added in step 6.
  1. First ensure your computer is connected to the same network as the board. Open your command line,[ enter wsl if on a windows system,] then type in ssh <username>@<hostname> where username and hostname are the ones set in step 6. You are prompted for your password, type it in and press Enter. If all is correct you are logged in as shown below. Notice the change from ‘sheunl@sheunz’ to ‘numnum@tarantula’.

  1. Now you are connected to the command line for the Raspberry, It time to enable the Remote Desktop feature, run sudo raspi-config you will get a command line menu for the Raspberry Configuration Tool
    • Select ‘Interface Options’ using the arrow button then Enter. Then select ‘VNC’. You will get asked ‘Would you like the VNC Server to be enabled?’ press Tab and press Enter on <yes>.
    • VNC server gets enabled and your get a box indicating that.
    • Download RealVNC viewer.
    • Setup the RealVNC viewer and open the app.
    • Connect using the hostname you added at step 6. You will be prompted to confirm SSH key fingerprint, click yes. Then prompted for your SSH username and password. Enter both and click okay.
    • Your should now see the Raspberry Pi OS Desktop in a new window.

Results should be a window like below.

Finally ! You have set up your Raspberry Pi board, have fun.

Making Custom Numbered List in CSS : Part 1

Creating a custom numbered list in CSS is quite simple. This can be done using a list or any block level element. We will be using the following CSS properties:

  1. counter-reset : To initialize our counter in the parent element.
  2. counter-increment : To specify our increment value for our counter.
  3. content : To output the numbers by replacing elements in the ::before or ::after Selector.

Below is a sample using counter function with block level elements.

See the Pen Custom List in CSS by Sheun (@sheunl) on CodePen.

Custom numbering is useful if you want to create complex numbering systems that are not readily available using <ol> element. or if you want to automatically add special characters to your numbering like brackets. Example below adds nested numbering to a list, using the counters function in this.

See the Pen Custom List in CSS 2 by Sheun (@sheunl) on CodePen.

Hope this provides a quick intro into custom numbered lists in CSS. Watch out for the second part.

Importance of software Testing

In a lot of solo projects testing is usually an after thought. Any team or even individual with any long term plans for a project should have test written into their code.

If your projects do not have tests they are exposed to the following issue.

  1. High rate of runtime error/bugs. Costing you customers.
  2. Time wasted from manually testing your code. Costing you time.
  3. High risk of falling out of compliance. Opening you up legal and financial risks.

Just because a project is small does not mean it should not have tests. As a matter of fact the best time to start implementing testing is when a project is small. Trying to add test to large and growing project is an ordeal unto itself.

Luckily key industries like finance, aerospace and automobiles, just to name a few mandate testing in order for products to meet standard. So if you want to create standard products it goes without saying too much. TEST! Want to be a better developer. TEST!! Do not wait for QA or a test team, at the very least have unit testing in your code.

Below are some links I am currently using:

  1. Link 1
  2. Link 2

Happy Testing!!

Quick one on Python random numbers sampling

I have been working on a project to generate random data using Python. Since I am not using this project for any security application I opted for the Python pseudo-random number generator random .

In order to randomly select items from a list three option presented themselves to me random.choice, random.choices and random.sample .

random.choice

Selects one item randomly from list of length n.

>>> import random
>>> random.choice([4,2,6,7,1])
6
>>> random.choice([4,2,6,7,1])
4
>>>

random.choices

Selects k items randomly from list of length n.

>>> import random
>>> random.choices([4,2,6,7,1],k=2)
[2, 6]
>>> random.choices([4,2,6,7,1],k=20)
[6, 4, 1, 6, 1, 1, 6, 7, 7, 2, 4, 4, 2, 2, 6, 1, 4, 6, 7, 4]

random.sample

Select k items randomly from list of length n, without replacement. Randomly select items are removed from the list, therefore if k > n there is an error.

>>> import random
>>> random.sample([4,2,6,7,1],k=3)
[6, 4, 1]
>>> random.sample([4,2,6,7,1],k=20)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/random.py", line 363, in sample
    raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative

Hopefully , I have given a concise introduction random item selection from a list in Python. Refer to the documentation for more functions and information.