# Today I Learned

This project is a collection of short write-ups on the things that I learn on a day-to-day basis across a variety of fields such as Computer Science, Mathematics, Software Engineering and Digital Design.

I consider this to be a microblog of sorts that can help me accumulate and share my knowledge with everyone! So far, I've published 75 short articles.

Hope you enjoy learning along with me! 😄

CSS+SCSS

# Use node-sass to minify your CSS

Published on November 7th, 2020

If you want to turn your .scss files to minified .css files but without using Webpack or Gulp, just install the node-sass package using npm package manager and then run this on your terminal:


sass scss/style.scss css/style.css --style compressed



And now, you can use your style.css file on production! 😆

Hope you found this tip useful!

This happened like two days ago, when one of the client sites went down. Upon inspecting the error logs, I found this:


SQLSTATE[HY000]: General error: 1835 Malformed communication packet



If you got the same error as the one above, don't worry, it's not your fault. According to this forum, a recent MariaDB update introduced a new bug for PHP versions < 7.3 that uses PDO and MySQL connectors. You can easily resolve this by simply upgrading it to PHP 7.3.

Hope this tip helps you out!

There are many ways to define constants in Laravel but I learnt a neat technique where you can define constants using an alias.

First off, create the following directory:


mkdir app/Constants



Next, create a file named MyConstants.php in the app/Constants directory and copy-paste the following code:


<?php
namespace App\Constants;

class MyConstants {
const HELLO = 'hello';
}
?>



Then, go to the config/app.php file and define your new alias:


'aliases' => [
// previously defined aliases...
'MyConstants' => App\Constants\MyConstants::class,
]



Lastly, execute the following commands to update your app's configuration:


php artisan config:clear
php artisan config:cache



After that, you can use your new constants anywhere (Controllers, Models or Blades) like this:


<?php
echo MyConstants::HELLO;
?>



Learning this new technique helps me keep the code clean and makes it easier to trace the constants.

Hope you find this tip useful!

Open up your text editor and use the following RegEx pattern to find and remove the duplicate lines:


^(.*)(\r?\n\1)+$  I found this technique on Regular-Expressions.info and I'm going to quote their explanation over here: The caret will match only at the start of a line. So the regex engine will only attempt to match the remainder of the regex there. The dot and star combination simply matches an entire line, whatever its contents, if any. The parentheses store the matched line into the first backreference. Next we will match the line separator. I put the question mark into \r?\n to make this regex work with both Windows (\r\n) and UNIX (\n) text files. So up to this point we matched a line and the following line break. Now we need to check if this combination is followed by a duplicate of that same line. We do this simply with \1. This is the first backreference which holds the line we matched. The backreference will match that very same text. If the backreference fails to match, the regex match and the backreference are discarded, and the regex engine tries again at the start of the next line. If the backreference succeeds, the plus symbol in the regular expression will try to match additional copies of the line. Finally, the dollar symbol forces the regex engine to check if the text matched by the backreference is a complete line. We already know the text matched by the backreference is preceded by a line break (matched by \r?\n). Therefore, we now check if it is also followed by a line break or if it is at the end of the file using the dollar sign. The entire match becomes line\nline (or line\nline\nline etc.). Because we are doing a search and replace, the line, its duplicates, and the line breaks in between them, are all deleted from the file. Since we want to keep the original line, but not the duplicates, we use \1 as the replacement text to put the original line back in. Hope you found this tip useful! Git # Rename a Git Branch Published on November 4th, 2020 Using branches are one of the most powerful features of Git and becomes a part of the software development process. Last night, I came across an issue where I created a new branch and committed my changes until the git tool rejected it because the branch was already created by someone else in the repository. Luckily, I was able to resolve this issue by renaming my branch using git branch -m command. Here's a short guide on how you can do that too! ## 1. Switch to the remote branch you want to rename  git checkout <your_old_branch>   ## 2. Rename the current remote branch  git branch -m <your_new_branch>   Proceed to the next step, if you've pushed your old branch to the remote repository. ## 3. Push the renamed remote branch  git push origin -u <your_new_branch>   ## 4. Delete the old remote branch  git push origin --delete <your_old_branch>   If you've come this far without any issues, you've successfully renamed your local and remote Git branch. Hope you found this useful! Say, you have a table named hobbies and wanted to display a list of hobbies based on user_id, you'd probably do something like this:  SELECT title FROM hobbies WHERE user_id = 8;   This would return a list of hobbies like this:  Boxing Coding Reading Fishing   That's simple but what if you wanted to display them in one row? Like this:  Boxing, Coding, Reading, Fishing   You can make use of the GROUP_CONCAT method to achieve the same result by executing the following SQL query:  SELECT GROUP_CONCAT(title, SEPARATOR ', ') FROM hobbies WHERE user_id = 8;   Nice, what if you wanted to view a list of hobbies of all users? In most cases, a table like this might have a many-to-many relationship, so in order to avoid possible duplicates, you can try this:  SELECT user_id, GROUP_CONCAT(title, SEPARATOR ', ') FROM hobbies GROUP BY user_id   Hope this tip helps you out! Sometimes, phpMyAdmin can be painful to use especially when you want to import/export a MySQL database. If you're not afraid of using the Terminal, try these commands to save your time: ## Import MySQL database  mysql -u username -p database_name < your_sql_file.sql   Before you run this command, please make sure that you've created the database_name schema in your database or else, you might get an error especially if the .sql file doesn't have a CREATE DATABASE statement. ## Export MySQL database  mysqldump -u username -p database_name > your_sql_file.sql   This command will export your database with the file name your_sql_file.sql to your current path. Hope this helps you out! Previously, I used to determine my Public IP address on Google Search by typing "What is my IP?" and I was good with it. Until, I thought of actually viewing it via the terminal itself. So, I wrote two lines of code in my ~/.bashrc file:  export myip="$(dig +short myip.opendns.com @resolver1.opendns.com)"
alias myip="echo $myip"   Alternatively, you could try this too:  export myip="$(dig TXT +short o-o.myaddr.l.google.com @ns1.google.com)"



Save the file and apply your new configuration by typing the following command:


source ~/.bashrc



That's it, now all you have to do is type myip in your terminal and it will display your Public IP address.

Hope you found this useful! 😀

Yesterday, I decided to try XFCE desktop environment and boy, it's really faster than the GNOME desktop environment.

As soon as I started to play around with it, I noticed a good amount of screen tearing and to my surprise, I came to know that the XFCE environment is known to have such issues.

After a few minutes of research, I was able to fix it. Here are the steps:

Note: This is done on Ubuntu 18.04 Bionic Beaver

If you dont have the package inxi installed in your system, do it right now:


sudo apt install inxi



After you're done installing, type the following command to find out which graphics you're using:


inxi -G



If you're using an Intel Graphics Driver, you'll probably get something like this:


Graphics:  Card: Intel Device 5926
Display Server: x11 (X.Org 1.19.6 ) driver: i915 Resolution: 1920x1080@60.00hz
OpenGL: renderer: Mesa DRI Intel Iris Plus Graphics 640 (Kaby Lake GT3e) (KBL GT3)
version: 4.6 Mesa 20.0.8



You can try go to Settings Manager->Window Manager Tweaks->Compositor" and enable **Synchronize drawing to the vertical blank. From what I've read, if you do that, it should stop but it didn't do anything for me.

If the above technique didn't work, go to /usr/shar/X11/xorg.conf.d/ and create a file for your graphics card named 10-intel.conf.

Copy-paste the following configuration into the file:


Section "Device"
Identifier  "Intel Graphics"
Driver      "intel"
Option "TearFree" "true"
EndSection



Save the file, reboot your system and look for any screen tearing issues. If you didn't face any, that means it worked! 😁

You'll get this error when you're hosting a Laravel project with using HTTPS/SSL protocol on localhost or 127.0.0.1:


cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)



I read some article on trying to install cacert.pem authorization certificate on your WAMP/XAMPP setup but it didn't really work out for me as I was running out of time.

So, I did a little digging and learnt that I can just modify the verify flag to false in the vendor/guzzlehttp/guzzle/src/Client.php file:


$defaults = [ 'allow_redirects' => RedirectMiddleware::$defaultSettings,
'http_errors'     => true,
'decode_content'  => true,
'verify'          => false, // changed it to false
];



By changing to it false, you'll not face that error again but please keep in mind, you should do this only if you're developing on localhost.

Happy coding!

Laravel

# Get pagination data by page number

Published on September 28th, 2020

By default, Laravel's paginator checks the value of the page based on the query string and uses that to display the results and also, it generates links to previous and next pages as well.

The paginate() method takes the following parameters by default:


public function paginate($perPage = null,$columns = ['*'], $pageName = 'page',$page = null);



So, if you want to fetch the pagination data of a specific page, then just write this:


$pageNumber = 5;$data = ExampleModel::paginate(5, ['*'], 'page', $pageNumber);   Hope you found this article useful! I was working on a project that dealt with generating large .zip exports and as a result, the storage/exports directory, which was used to store all the .zip exports, ended up going all the way up to a whopping size of 10 gigabytes! 😮 I resolved it by calling the Filesystem package in my controller:  use Illuminate\Filesystem\Filesystem;   Then simply, create a new instance and define the directory you wanted to clear: $folder = new Filesystem;
$folder->cleanDirectory('storage/exports');   Hope this helps you out! Pause the current process using Ctrl + Z, which will send it to the background and then type bg to allow the process to run in the background. Alternatively, you can add a & after the desired process you wanted to execute and it'll automatically execute it as a background process. Hope this helps you out! Tired of trying to look for errors in DevTools by scrolling a long list of HTTP responses? Open up your Chrome DevTools and hit the Network tab and then try filtering the responses by typing the status-code property in the filter box. It comes in handy when you want to narrow down to a specific list of HTTP responses. For instance, if you're looking for responses with error 404, you can filter it by typing like this: status-code:404. Another trick is, you can filter out the responses that you don't want to see by just adding a hyphen like this: -status-code:200. Hope this tip helps you out! Are you facing the same error as this article's title? Then this article might help you out. If you're developing applications using HTTP/SSL Protocols (regardless, you should!) on Laravel, by default, you'll be using Laravel's encrypter but in it's official documentation, it says: Before using Laravel's encrypter, you must set a key option in your config/app.php configuration file. You should use the php artisan key:generate command to generate this key since this Artisan command will use PHP's secure random bytes generator to build your key. If this value is not properly set, all values encrypted by Laravel will be insecure. Just execute the following command in your root directory:  php artisan key:generate   If the error still persists, try clearing the cache by doing the following:  php artisan config:cache php artisan cache:clear php artisan config:clear   Hope you found this article useful! Apache + WAMP # Enable HTTPS/SSL on WAMP Server Published on September 13th, 2020 Building a website with HTTPS/SSL in mind can help resolve a lot of problems when you're going to deploy it on production server. So, here's a small tutorial on how to enable HTTPS mode and install SSL certificate on your local WAMP Server. Note: This tutorial assumes that you have a Windows PC and have installed WAMP Server 3.2.0 in your local system, if not, download it from here. ## Download OpenSSL Based on your system's architecture, you can download either a 32 or 64-bit installer. You can find the latest version of OpenSSL from here. While installing, please make sure all the options selected are default. ## Generate SSL Key and Certificate Open your terminal or command-line prompt and navigate to the following folder:  cd "C:\Program Files\OpenSSL-Win64\bin"   Next, you need to create a private key. While generating a private key, you'll have to enter a passphrase, it can be anything but make sure that you can remember it for the next step 😂. Execute the following command:  openssl genrsa -aes256 -out private.key 2048   Good, now let's generate our certificate and in this step, you'll be prompted with several questions. You can fill as per your wish or just hit "Enter" to leave it as default. The only thing that matters is Common Name and this should named as localhost Execute the following command:  openssl req -new -x509 -nodes -sha1 -key private.key -out certificate.crt -days 36500   ## Move the certificate and key to Apache's directory Create a folder named keys and move both private.key and certificate.crt to this directory: C:\wamp64\bin\apache\apache2.4.41\conf. ## Modify your httpd.conf file You have to uncomment 3 lines from C:/wamp64/bin/apache/apache2.4.41/conf/httpd.conf:  LoadModule ssl_module modules/mod_ssl.so Include conf/extra/httpd-ssl.conf LoadModule socache_shmcb_module modules/mod_socache_shmcb.so   ## Modify your httpd-ssl.conf file Go to C:/wamp64/bin/apache/apache2.4.41/conf/extra/httpd-ssl.conf and modify the following parameters:  DocumentRoot "c:/wamp64/www" ServerName localhost:443 ServerAdmin admin@youremail.com ErrorLog "${SRVROOT}/logs/error.log"
TransferLog "${SRVROOT}/logs/access.log" SSLSessionCache "shmcb:${SRVROOT}/logs/ssl_scache(512000)"
SSLCertificateFile "${SRVROOT}/conf/keys/certificate.crt" SSLCertificateKeyFile "${SRVROOT}/conf/keys/private.key"
CustomLog "${SRVROOT}/logs/ssl_request.log"   DocumentRoot is the location of where your website files are located. ServerName can be anything but preferable to use localhost. ## Restart your WAMP Server Just restart your WAMP Server for the changes to take effect. If the WAMP icon turns green, you're good else, an typo or syntax error must have occurred. Hope you found this tutorial useful! 😀 Whenever you develop a website using the LAMP or WAMP stack, you'll want to access the website, locally, via different systems and devices solely for testing purposes. ## Modify your VirtualHosts configuration Setting up your WAMP Server for LAN access only requires you to tweak your VirtualHosts configuration file found in C:\wamp64\bin\apache\apache2.4.41\conf\extra\httpd-vhost.conf  <VirtualHost *:80> ServerName example.test ServerAlias example.test DocumentRoot "c:/wamp64/www/yourprojectname" <Directory "c:/wamp64/www/yourprojectname/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> </VirtualHost>   Oh, if you're using Linux, you'll find the file 000-default.conf in /etc/apache2/sites-available directory. ## Update your hosts file If you type the URL of the website that you want to visit, the computer will first refer to the hosts file and then it'll go out to fetch DNS information. So, if you want http:\\example.test url to point to your local system, you just have add it in your hosts file: Open the hosts file(C:\Windows\System32\drivers\etc\hosts) using a text editor and add this line to your hosts file:  127.0.0.1 example.test   Once done, save the file and restart your WAMP Server and you're all set to go! Hope you found this tip useful! I'm working on an eCommerce project and I encountered a really weird problem, whenever I saved items into my cart and proceed to the checkout page and then go back to previous page, my cart isn't updated until I refresh the page. Honestly, I thought this was a bug until I came around to learn about Back-Forward Caching a.k.a bfcache, which allows the user to navigate between pages faster. That's a good thing, though! But that didn't help resolve my issue, so I thought of going around with a tiny hack:  window.onpageshow = function(event) { if (event.persisted) { window.location.reload() } };   The code above will look any persistence of the onpageshow event. Initially, it's set to false and if the page is loaded from bfcache, it'll set to true. I wouldn't really consider this as a solution as it only worked on Safari instead of Chrome or Firefox. But hey, it gets the job done! 😂 If you want to reload the current page in your browser without any query string or parameters, here's how you can do it:  window.location = window.location.pathname;   By doing so, it'll preserve the HTTP/HTTPS protocols of the URL and also remove the fragments that start with a #. If you want to preserve the fragments, you can try this:  var reloadURL = window.location.pathname; var fragments = (window.location.part === undefined) ? "" : "#" + window.location.part; window.location = reloadURL + fragments;   Hope you found this useful! I thought of getting back into competitive programming again and started practicing my python coding-chops on Codewars. Here's a neat trick on how to extract unique characters from a string:  from collections import OrderedDict word = "HelloWorld" uniq = ''.join(OrderedDict.fromkeys(word).keys()) print(uniq) # prints HeloWrd   Using OrderedDict allows you to preserve the order in which the keys are inserted as a normal dict doesn't track the order. Hope you found this useful! Ever process a file that's larger than 2GB and got an error that said something like this: Maximum execution time of 30 seconds exceeded Though, PHP doesn't have an efficient way of processing files of large sizes, you can prevent your web application from timing out by adding this to your code:  <?php // 300 seconds == 5 minutes ini_set('max_execution_time', 300); ?>   Hopefully, some day, this might come in handy for you! 😜 PHP # Increase memory limit in PHP Published on August 23rd, 2020 Last month, I was building a web application that collected a lot of data via form submissions. I wrote a method to export attachments and form data by zipping them all together. It worked for a smaller archives but as the records grew larger, I got a fatal error which said that I've exhausted the PHP's memory limit. So, I found an easy way to increase the memory limit to 1024MB (1GB) like this:  <?php ini_set('memory_limit', '1024M'); ?>   Before you write this stub in your script, make sure you have enough resources in your system or else, it'll go splat! PHP # Input sanitization with PHP Published on August 23rd, 2020 This can come in handy when you're dealing with user inputs during a form submission and in most cases, your web application will be using a database query to store the data. ## Using filter_var() This method uses a number of flags to validate and sanitize a string. Here are some examples I have tried: ### Removing special characters Want to strip out all tags and certain characters? Try this:  <?php$str = "<h1>Hello World</h1>";
$filtered = filter_var($str, FILTER_SANITIZE_STRING);
echo $filtered; ?>   ### Integer validation You can check if the input is an integer and if it's a value between 1 and 20:  <?php$x = 10;
$min = 1;$max = 20;
$options = [ "min_range" =>$min,
export PATH=$GOPATH/bin:$GOROOT/bin:$PATH   Save your .bashrc file and update the current shell session:  source ~/.bashrc   ## Verify your installation Type the following command to ensure that your Go installation is successful:  go version go1.14.6 linux/amd64   ## Hello, world! As per traditions, whenever you learn a programming language, you start off with a "Hello, world!" program, so here it is:  package main import "fmt" func main() { fmt.Printf("Hello, world!\n") }   ## Conclusion I just started learning it today and at first, you might have the tendency to write code in Go the same way you write in any other language but beware, it doesn't work that way. It forces you to write good code including the way it formats the code using the gofmt tool. Lots of cool things are coming! Stay tuned for more. Ever compressed your project directory but forgot to delete that useless file or folder and turns out the compresed file is larger than it's supposed to be? Here's a quick solution you can try: If you want to delete a file inside a .zip file, try this:  zip --delete file.zip "file.ext"   And if you want to delete a folder, try this:  zip --delete file.zip "folder/*"   Hope this helps you out! The usual approach of counting the number of uppercase and lower letters in a string is done by using a counter and a loop:  var upperCount = 0; var lowerCount = 0; var str = "AbCdEfGhiJkL"; for(var i=0; i<str.length; i++){ if(str[i] == str[i].toUpperCase()){ upperCount++; } else{ lowerCount++; } }   That's nice but here's shorter and faster implementation:  var str = "AbCdEfGhiJkL"; var lowerCount = str.length - str.replace(/[A-Z]/g, '').length; var upperCount = str.length - str.replace(/[a-z]/g, '').length;   The lowerCount variable is taking the difference of the lengths between the original string and the string with lowercase letters only because the .replace() method replaced the pattern of uppercase letters [A-Z] with empty spaces. The upperCount variable does the opposite of what the lowerCount variable does. Hope you found this trick useful! Let's say you have the following string and you must replace all occurrences of "Hello" with "Bye":  var str = "Hello Hello Hello World";   You may think of using the .replace() method to solve this problem:  var newStr = str.replace("Hello", "Bye")   But unfortunately, it only replaces the first occurrence in the string:  console.log(newStr); // returns "Bye Hello Hello World" as the output.   Using the power of Regular Expressions, you can replace all occurrences in one go:  function replaceAll(str, search, replace){ var re = new RegExp(search, "g"); return str.replace(re, replace); }   Now, when you execute the following, you'll get a string that replaced all occurrences:  var newStr = replaceAll(str, "Hello", "Bye"); console.log(newStr); // returns "Bye Bye Bye World" as the output.   Until next time, then! Let's say, you have a multidimensional array like this: $cars = [
[
"id" => 1,
"name" => "Mercedes Benz",
"color" => "Black"
],
[
"id" => 2,
"name" => "Toyota",
"color" => "Red"
],
[
"id" => 3,
"name" => "Toyota",
"color" => "White"
],
[
"id" => 4,
"name" => "Nissan",
"color" => "Grey"
],
];



And say, you want to be able to return unique cars by name or color, use this method:


function multi_array_unique($array,$key) {
$i = 0;$temp_array = [];
$key_array = []; foreach($array as $val) { // insert only unique keys if (!in_array($val[$key],$key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val; }$i++;
}
return $temp_array; }   Call this method from anywhere in your code like this: $unique_cars = multi_array_unique($cars, "name"); dd($unique_cars);



And now, you'll get something like this:


[
[
"id" => 1,
"name" => "Mercedes Benz",
"color" => "Black"
],
[
"id" => 2,
"name" => "Toyota",
"color" => "Red"
],
[
"id" => 4,
"name" => "Nissan",
"color" => "Grey"
],
];



You might wonder why I tried this instead of PHP's array_unique() method and the reason I didn't use it is because it doesn't support multidimensional arrays.

Hope you found this useful!

This trick comes in handy whenever you wanted to reuse a table, perform data migrations or maybe even take a backup of the table before any of your experiments mess up your data.

Executing the following query will help you create a new table with the structure of the old table:


CREATE TABLE schema.new_table LIKE schema.old_table;



If you want the data as well, try this:


CREATE TABLE schema.new_table LIKE schema.old_table;
INSERT schema.new_table SELECT * FROM schema.old_table;



You can use this query to copy tables from one schema to another schema too. Hope this helps you out! 😄

Finding the difference between two sets i.e. Set A and Set B is basically returning a new set that contains values of Set A that don't exist in Set B or vice-versa.

Here's an example:


var a = [1,2,3,4,5];
var b = [1,1,2,3,4];



I wrote a shorter implementation using JavaScript's .filter() method:


function array_diff(a,b){
return a.filter(i => b.indexOf(i) === -1);
}



Once you execute this method, you'll get the following as a result:


var c = array_diff(a,b);
console.log(c) // returns [5]



## BONUS: What does the .filter() method do?

This method returns a new array with elements that pass the conditions provided by a callback function.

If the conditions aren't passed, you'll receive an empty array.

In this article, (i => b.indexOf(i) === -1) is considered as the callback function in which the i refers to the index of the current element of array A and is then used as a parameter to check if the element doesn't exist in array B.

The neat thing about this method is that it doesn't mutate on the array that it's being called from.

Using PHP's in-built function, parse_url, you can write a helper method to pull the channel ID off a YouTube URL especially if you're pulling videos using YouTube's Data API. Here's the code:


public function extractChannelID($url){ // Parse the link and trim any whitespaces$parsed_link = parse_url(rtrim($url, '/')); // Return the channel ID if it matches the pattern if (isset($parsed_link['path']) && preg_match('/^\/channel\/(([^\/])+?)$/',$parsed_link['path'], $matches)) { return$matches[1];
}

throw new Exception("This {$url} is not a valid YouTube channel URL"); return null; }   Writing tiny methods like these can help save time and be reusable in more than one context. Hope you find this tip useful! 😁 Whenever you're sending a bunch of files or an archive that contains sensitive or confidential information, it's wise to encrypt before you send it to the person that you intend to. Using zipcloak, you'll be able to encrypt files within your existing archive. Do the following after you've created a zip archive:  zipcloak files.zip   Now, you'll be prompted twice to enter a new password and verify your entered password. If they match, your archive will get encrypted. So whenever, you try to unzip or open using an Archive Manager, you'll be prompted to enter the password or else, you won't be able to access it. You also have the choice of not encrypting the original archive and creating a new one instead, just like this:  zipcloak files.zip -O encrypted.zip   On the other hand, if you do wish to remove the encryption from your archive, just type the following:  zipcloak -d files.zip   And you'll be prompted again to enter your password before it removes it's encryption. Hope this helps you out! 😁 Although, Laravel is a good framework, it's quite heavy when it comes to executing queries especially if you're using the Eloquent ORM instead of the normal query builder. But Laravel does offer the option of caching your queries in the server and will only make calls to your database if there's a change in content. Quite handy when you're having a content-heavy website and huge amount of user traffic. Using the Cache class, you can cache your queries like this: $apples = \Cache::rememberForever('apples_cache', function(){
return FruitsModel::where('item_name', 'LIKE', '%apples')
->get();
});



In the above example, apples_cache is the key that stores your queries of apples forever and which will be used to obtain your cached results from the server.

Oh, be sure to create distinctive names for different types of queries or else, you'll end up being confused! 😜

You can also give it a time limit in milliseconds:


$apples = \Cache::remember('apples_cache', 300000, function(){ return FruitsModel::where('item_name', 'LIKE', '%apples') ->get(); });   Hope this tip helps you out! 😀 Algorithms # Looping infinitely around an array Published on July 4th, 2020 Sometimes, I find myself in a situation where I might have a fixed array of colors, text, numbers or something like that but I want to loop around infinitely like a carousel. Let's say we have an array like this:  var colors = ["#111", "#222", "#333"];   The code is an array of three colors that we want to apply to, hmmm, say a list of HTML DOM elements like <div> containers or any element that you prefer. In this example, we'll add some colors to a bunch of <div> elements that has the classname .card or we'll just call them "cards". ## Behold, the Modulus operator! You may think of writing different conditions or loops to achieve a solution but a more elegant one is by using the Modulus operator a.k.a the Remainder operator (%). Using this operator gives you the remainder after the division of a number. Hmm, confused? Okay, here's a simple example of how a Modulus operator would be like: In plain english, if you have 10 apples and you divide them by 4 and by doing so, you'll end up with 2 sets of 4 apples and the remaining set would be 2 apples. Thus, the remainder is 2. Did that make sense? If not, then try the following code in your browser:  var x = 10 % 4; console.log(x); // output will be 2   Let's say we have 10 "cards" and we want every 3 three cards to have 3 different colors, we must just define a way to determine the index of each color while iterating through a loop of cards. So, we can easily get the index by doing so:  var currentColor = colors[i % colors.length-1];   Here's the full code:  var elements = document.querySelectorAll('.card'); for(var i=0; i<elements.length; i++){ var currentColor = colors[i % colors.length-1]; elements[i].style.backgroundColor = currentColor; }   The following code will apply the colors to each "card" with respect to it's order and will reset back to the first color once it's reached it's last color based on the remainder of the next iteration in the loop. Read about Modulus Operation to know more about it. You can manually force HTTP to HTTPS after enabling your SSL certificate by adding the following condition at the beginning of your .htaccess file in your public directory:  RewriteCond %{HTTP:X-Forward-Proto} !=https RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]   Save your file and restart your Apache server and now, your web application will redirect all your users to https:// instead of http:// URLs in the future. As part of a project that I was working on, I learnt about HTTP Strict Transport Security protocol which tells the browser about making future web requests over HTTPS only. So, even if you attempt to use http://, the browser will force you to use https:// URLs in the future. You can enable it by writing this header in your .htaccess file in your public directory:  Header always set Strict-Transport-Security "max-age=31536000" env=HTTPS   Please note that once you enable this protocol, your web application is committed to using SSL i.e. you won't be able to use insecure HTTP for your web application. In my current Arch Linux installation, I decided to use a window manager called i3. It's really awesome and it comes with a really lightweight terminal emulator called urxvt. It's very minimal and I lked it but when I tried to copy-paste text from one terminal to another, I wasn't able to. However, thanks to the internet, I did some research and figured a way out. ## 1. Install xClip First, you need to ensure that you have installed the xclip package, which will be used to copy-paste text in the emulator. Type the following command to install the package:  pacman -S xclip   ## 2. Activate Clipboard using Perl Now, you have to paste these custom commands into your clipboard file, which is found in /usr/lib/urxvt/perl directory:  # paste selection from clipboard sub paste { my ($self) = @_;
my $content = /usr/bin/xclip -loop 1 -out -selection clipboard ;$self->tt_write ($content); } # copy text to clipbard on selection sub on_sel_grab { my$query = $_[0]->selection; open (my$pipe, '| /usr/bin/xclip -in -selection clipboard') or die;
print $pipe$query;
close $pipe; }   ## 3. Modify your .Xresources Add these keybindings to your .Xresources file:  URxvt.keysym.Shift-Control-V: perl:clipboard:paste URxvt.iso14755: False URxvt.perl-ext-common: default,clipboard   After adding it, refresh your .Xresources settings:  xrdb -merge .Xresources   Reboot your terminal and try selecting some text from your terminal using your mouse and paste it using Ctrl+Shift+V and it should work! That's it! Enjoy 😃 Yesterday, I thought of testing my Arch Linux system's audio and turns out, I didn't even install it yet! 😒 Well, thanks to ArchWiki, it was simple enough to install to make the audio work on my old laptop. Just install the following packages:  pacman -S alsa-firmware alsa-lib alsa-utils   Reboot the system once you're done installing the packages. Depending on your window manager, you should be able to see your sound icon being active. ## Bonus: Bash script to control your volume from the terminal In my current laptop, I still haven't mapped out the keys to control the audio volume, so I thought of writing a small method in my .bashrc file, so that I can control it from my terminal. Open your favorite text editor and Add this method in your .bashrc file:  # simple volume control volume(){ x=5 if [$1 == 'up' ]
then
amixer set Master $x%+ &> /dev/null elif [$1 == 'down' ]
then
amixer set Master $x%- &> /dev/null elif [$1 == 'toggle' ]
then
amixer set Master toggle &> /dev/null
fi
}



Save the file, close your edit and refresh your file by typing:


source .bashrc



Now, it should work when you type any of these commands:


volume up
volume down
volume toggle



Hope this tiny script helps you out!

As I was configuring Arch Linux setup on my old HP 8460p laptop, I noticed that I wasn't able to access any site using Chrome or Firefox as I was faced with a weird error:

I was quite confused and thought it might be an issue with my WiFi card or probably some server issue but turns out it was neither of them.

On the side of my screen, I noticed my system time was displaying 4 hours ahead of the current local time, which is wrong. So, I did a little research and turns out my suspicions were correct, it's a time-related issue.

## How is time related to secure websites?

Well, each website that uses SSL or that begins with https:// are only valid for a period of time before getting expired. If the website that you're trying to visit presents a certificate with a time and date that doesn't match with your system's clock, Firefox will prevent you from accessing the page.

## How to fix it?

Actually, the fix is quite simple. All you have to is just set the correct date and time on your system and you're good to go!

If you're using Linux, just do the following:

### 1. Set up your timezone

You can look up for your timezones by executing the following:


timedatectl list-timezones | less



Once, you've found your timezone, execute the following by replacing Continent/Country with your timezone:


timedatectl set-timezone Continent/Country



### 2. Manually set your local time

Execute the following to set up your time, locally on your system:


timedatectl set-time "yyyy-MM-dd hh:mm:ss"



### 3. Set the hardware clock from the system clock

The following command sets the hardware clock from the system clock:


hwclock --systohc



Now, that you've executed them, you should be able to view the correct time on your system by executing timedatectl status and you should see something like this:


Local time: Sun 2020-06-14 21:04:04 +04
Universal time: Sun 2020-06-14 17:04:04 UTC
RTC time: Sun 2020-06-14 17:04:05
Time zone: Asia/Dubai (+04, +0400)
System clock synchronized: no
NTP service: inactive



Although, this issue was time-related, you may face the same kind of error for various other reasons. Try reading more on how to troubleshoot errors like these from Mozilla's official documentation.

Do you want to transfer files remotely from one UNIX-based system to another? Try using the scp tool, which is a shorthand for Secure Copy Protocol. It's based off the SSH protocol using it as a means to securely transfer files from a local machine to one or more remote machines.

Here's a code snippet that can help you out to transfer from computer A to computer B:





And transfer from computer B to computer A:





Oh, before you transfer files to another computer, make sure that you have permissions to access it first. If you don't have one, then create a new account using useradd on your remote system.

Recently, I thought of playing around with Arch Linux to learn more about Linux under-the-hood and to see if it can become my new daily driver.

As I booted from live USB, I tried connecting to my WiFi using wifi-menu but it never worked after selecting my network name and entering the credentials.

So, I did a little bit of research in ArchWiki and forums and I figured a way to set it up manually using netctl by myself.

netctl is a network profile manager and it's apparently an Arch Linux project.

Before you begin to set up your WiFi connection from your computer, check if your network interface is being detected:


iwconfig



Since it's a WiFi connection, your interface most probably must be wlan0. If you see it, then set the interface up:





## 2. Scan for networks

Now, that your interface, use it to scan for your WiFi network:


iwlist wlan0 scan | less



Once, you execute this command, you must be able to see your WiFi's SSID (or network name).

Now, put your interface down for a while:





## 3. Create a network profile

Alright, go to /etc/netctl/examples/ directory and make a copy of the wireless-wpa file to the /etc/netctl directory:


cd /etc/netctl/examples
cp /etc/netctl/examples/wireless-wpa /etc/netctl/your-wifi-name



Now, go back to /etc/netctl/ directory and open the your-wifi-name file with your preferred text editor and edit the following only:


ESSID: your-wifi-name



After you're done editing, save the file.

## 4. Test network profile

To test if your profile is working, do the following:


netctl start your-wifi-name



In case, you get an error, try doing this:


ip link set dev wlan0 down
netctl start your-wifi-name



If you're able to ping, then it works. Else, edit your network profile and try connecting to it again.

## 5. Enable network profile

If you've reached this stage that means your network profile must be working fine. Just do the following to enable the network profile to run the internet throughout the setup:


netctl enable your-wifi-name



If you have a static site or a blog generated using a static-site generator but want to add a simple search functionality? This could be of your interest.

I'll take you through an example on how to build a simple search engine using a JSON file and AJAX requests.

## 1. Generate a JSON dump of your site

Although, it's not a database but it can act as an alternative to having one. Your JSON dump can contain any metadata that you wanted your users to search in your site. In my case, I thought of allowing the user to search title and category.

## 2. Build search functionality

I won't go through the aspects of UI design in this article as I feel that it's subjective and depends on one's preferences but let's keep it simple enough for this tutorial.

Before you begin writing the function, place this component in your HTML template:


<div class="searchbox">
<input id="searchinput" type="text">
<div id="searchresults">
<ul></ul>
</div>
</div>



Anyway, here's the function and you can place it directly on your template or in a separate .js file:


var _url = "path-of-your-file.json";

$(document).ready(function(){$('#searchinput').keyup(function(e){
var keyword = $(this).val(); var code = e.keyCode ? e.keyCode : e.which; if(code == 13){$.ajax({
url: _url,
type: "GET",
async: false,
}).done(function(data){
var results = "";
if(data.articles.length > 0){
$.each(data.articles, function(key, value){ if(v.title.search(pattern) != -1 || v.category.search(pattern) != -1){ results += <li><a href="${v.slug}">${v.title}</a></li>; } });$("#searchresults ul").html(results);
}
});
}
});
});



That's it! Now, when you execute your script, you should be able to view your search results just like as if it were using a database.

If you want to make it similar to mine, please feel free to inspect the code on the browser or go to my repository to see how it works.

You can make use of the built-in json package in Python to read and write JSON data to a file.

## Writing JSON to a file

You can store the information in a dictionary or dict object, which can contain any type of data like integers, booleans, arrays or nested objects.

By using a dict object, the json package will transform your dictionary into a serialized JSON string.


import json

dataObj = {}
dataObj['posts'] = []
dataObj['posts'].append({
'title': 'Hello world',
'category': 'Introduction',
'slug': 'hello-world'
})

with open('data.json', 'w') as file:
json.dump(dataObj, file)



## Reading JSON from a file

Reading is as easy as writing to a file. Using the same package again, we can parse the JSON string directly from the file.


import json

with open('data.json', 'r') as file:
for item in data['posts']:
print 'Title: ' + item['title']
print 'Category: ' + item['category']
print 'Slug: ' + item['slug']



I read about different package alternatives like simplejson but I guess for now, this is a great way to get started especially, if you're working with web applications and are interacting with a serialized JSON data on a daily basis.

Today, I wrote a simple method that fetches images from the database via AJAX and also, I defined an empty object as a default parameter:


function fetchImages(obj={}){
// some code here...
}

fetchImages();



The default obj parameter would contain extra parameters like id, slug and page, which would be then used to fetch a particular group of images, else, it'll fetch a random set of images.

This method worked fine in Google Chrome and Mozilla Firefox but not in Internet Explorer. I thought of inspecting the code and I was facing weird errors like undefined or Expected: ')' on the IE console.

Luckily, I had compared it to the other methods that didn't have any default parameters, so I did a little research and turns out that according to Mozilla's documentation, default function parameters are proposed by the ES6 syntax and at this point, I realized that Internet Explorer doesn't support ES6 syntax. What a bummer! 😒

However, there's a way to prevent this from happening by rewriting the method like this:


function fetchImages(obj){
// Check if obj is defined, else make it assign it as an empty object.
var data = obj || {};

// some code here...
}



And BAM! The method worked flawlessly just as it's intended to do so. 😎

Addtionally, you may refer to the ECMAScript 6 Compatibility table that you might find it quite helpful to check browser compatiblity for Internet Explorer versions 11 and under.

Algorithms

# Build a menu tree using recursion

Published on June 3rd, 2020

Hmm, what is the most efficient way to build a menu tree? 😅

Most people would go for a brute force solution if it's a straightforward menu but would that be possible if we intend to create multiple levels of menu items?

Sure, you could but as the number of loops increases, the complexity of time increases too. Not to forget, you'll end up writing code that'll look messy and unscalable.

I always loved the idea and simplicity of using recursion. So, I thought of exercising my recursion skills by writing a method that can generate a dynamic menu with x number of parent and child menu items.

The following example is written in PHP:



class FooController extends Controller {
protected $menuHTML = ""; private function menuItems() { return [ [ 'title' => 'Item 1', 'link' => '/item-1' ], [ 'title' => 'Item 2', 'link' => '/item-2', 'child_items' => [ [ 'title' => 'Item 2.1', 'link' => '/item-2.1' ], [ 'title' => 'Item 2.2', 'link' => '/item-2.2' ], ] ], [ 'title' => 'Item 3', 'link' => '/item-3' ], [ 'title' => 'Item 4', 'link' => '/item-4' ], ]; } // Build a menu tree private function buildMenu($menu) {
foreach($menu as$menuItem){
$this->menuHTML .= '<li class="item">';$this->menuHTML .= '<a href="'.$menuItem['link'].'">'.$menuItem['title'].'</a>';

// Check if it has any child items
if(array_key_exists("child_items", $menuItem){$this->menuHTML .= '<ul class="submenu">';
$this->buildMenu($menuItem['child_items']);
$this->menuHTML .= '</ul>'; }$this->menuHTML .= '</li>'
}
}

private function getMenu($menu) {$this->buildMenu($menu); return '<ul class="mainmenu">'.$this->menuHTML.'</ul>';
}

public function __construct() {
pre($this->getMenu($this->menuItems());
die;
}
}




Once you run it, you'll see something like this:


<li class="item"><a href="/item-1">Item 1</a></li>
<li class="item"><a href="/item-2">Item 2</a>
<li class="item"><a href="/item-2.1">Item 2.1</a></li>
<li class="item"><a href="/item-2.2">Item 2.2</a></li>
</ul>
</li>
<li class="item"><a href="/item-3">Item 3</a></li>
<li class="item"><a href="/item-4">Item 4</a></li>
</ul>



There a lot of ways to achieve this same result using recursion but it sure is easier to read, scalable and extensible, ain't it?

JavaScript

# Allow inline elements in CKEditor

Published on June 1st, 2020

Using CKEditor is awesome but I hate it when it removes inline elements like <span>, <i> or any DOM elements that contain attributes like classnames or ID, by default.

Well, CKEditor's documentation states that you can allow it by adding this line to your configuration:


var editor = CKEDITOR.replace('textarea_edit',{
allowedContent: true,
});



After adding this line, CKEditor will stop removing those elements from your HTML content but it's also open to all tags.

You can set rules to allow only specific ones like this:


var editor = CKEDITOR.replace('textarea_edit',{
allowedContent: 'span; i; ul; li; a[!href]'
});



Hope this helps you out! 😊

Using the event.currentTarget property which belongs to the Event interface can help you in many ways to identify target of the current event especially if you want to fetch attributes or modify the classname of an element that belongs to a group of elements sharing the same classname.

There are many examples but I chose to write a small snippet of highlighting a tab:


function highlightTab(e){
/*
Find elements that has the classname 'active'
and remove them
*/
if(document.querySelector('div.tab_item.active') !== null){
document.querySelector('div.tab_item.active').classList.remove('active');
}

// Add active class to target node
e.currentTarget.className += " active";

// Add active class to target's child node

// Add active class to target's parent node
// e.currentTarget.parentNode.className += " active";
}



Read Mozilla's official documentation to know more about getting the current target of an event and it's compatibility with different web browsers.

Algorithms and Data Structures

# Queues & Stacks

Published on May 30th, 2020

Let's look at the differences between the two data structures:

1. Queues: First-In First-Out
2. Stacks: Last-In Last-Out

## Queues

This follows a First-In First-Out processing order i.e. the first element added to a queue will be processed first. A queue should support two operations:

• Enqueue
• Dequeue

### Enqueue

Adds the element to the tail of a queue. The tail position gets incremented.

### Dequeue

Removes the first element of a queue i.e. the head element. Once, it's removed, the subsequent element becomes the new head element of the queue. The position of the new head element gets incremented and the previous one is assigned a negative integer like -1 or some garbage value.

Implementation of a standard queue using C++:


class Queue {
private:
int pos;
vector<int> data;

public:
Queue() {
pos = 0;
}

bool enqueue(int value) {
data.push_back(value);
return true;
}

bool dequeue() {
if(isEmpty()){
return false;
}
pos++;
return true;
}

int front() {
return data[pos];
}

bool isEmpty() {
return pos >= data.size();
}
}



In terms of memory management, a standard Queue is quite inefficient and incapable of handling dynamic memory.

## Stacks

This follows a Last-In First-Out processing order i.e. the last element added to a queue will be the first to be removed. Just like queues, it has two simple operations:

• Push
• Pop

### Push

Each element is pushed towards the end of the stack. Think of it as a card deck where you stack a card on top of another card.

### Pop

It removes the most recent element i.e. the newly added element from the stack.

Implementation of a stack using C++:


class Stack {
private:
vector<int> data;
public:
void push(int value) {
data.push_back(value);
}

bool isEmpty() {
return data.empty();
}

int top() {
return data.back();
}

bool pop() {
if(!isEmpty()) {
data.pop_back();
return true;
}
else {
return false;
}
}
}



Unlike queues, stacks are easier to implement and pretty efficient at managing dynamic memory.

Oh, if you ever get to use these, don't worry about implementing them, nearly all programming languages have their own implementations of stack and queue that comes with it's own standard library.

If you've ever come across this type of error when you're trying to fetch parameters of the current route:


Symfony\Component\Debug\Exception\FatalThrowableError: Call to member function parameters() on null



It's probably because the route doesn't exist, which is why it failed to call the parameters() function. It can be easily resolved by checking if the route exists before calling the function:


namespace App\Http\Controllers;
use Route;

class FooController extends Controller {
public function __construct(Request $request){ // insert code here... } public function foo(Request$request){
$params =$request->route() ? Route::current()->parameters() : '';
return $params; } }   Although, the sample code above is to fetch parameters of the current route, you can apply this before calling any method from the Route class. This works for version 5.2 and above. If you don't want the current element to be selected in an array of elements that belongs to same class or type, just use the .not() method like the example below: $(".btn").click(function(){
$(".btn").not(this).text('selected'); });   The above code will change the text for all buttons except the current element. First, you need to view what's inside of the .zip archive:  unzip -v archive.zip   Once, you've found the folder you wanted to extract, just type this:  unzip archive.zip "folder_to_extract/*" -d .   In this example, we're going to change a list of .txt files to .md files:  #!/bin/bash shopt -s nullglob files=($(ls -v *.txt))

for file in "${files[@]}" do mv${file} ${file}.md done   You can use modify this script to rename any extension you want. If you wanted to remove a specific pattern in a list of files, like the ones below:  23_2020_03_01_article-three.md 22_2020_02_01_article-two.md 21_2020_01_01_article-one.md   You can simply do that using Regular Expressions and the rename tool:  rename 's/[0-9]+_[0-9]+_[0-9]+_[0-9]+_//' *.md   Now, the desired output should look like this:  article-three.md article-two.md article-one.md   This should come in handy if you're lazy to rename each file manually! :) Terminal # Zip a file Published on May 25th, 2020 This comes in handy especially whenever you want to download multiples files from a server or take backups.  zip [option] output_file input1 input2   For example: if you want to zip an entire directory with it's file contents, just do this:  zip -r myfiles.zip folder/   Linux # View hardware info Published on May 25th, 2020 Want to check the specs of your system? Just type this:  lshw   Too long? Then type this for a shorter version:  lshw -short   Linux # View battery status Published on May 25th, 2020 This comes in handy if you're using the terminal in full screen but still want to know your battery life. Just type the following:  upower -i /org/freedesktop/UPower/devices/battery_BAT0   If you're hosting a laravel project via cPanel, chances are that it could be a shared hosting server and that means you can't really use php artisan storage:link for this. But don't worry, there's another way to this. Just follow the steps below: ## 1. Create a symlink In your public_html/public directory, remove the storage folder. Next, create a symlink.php file in your public_html directory and add the following code: $targetFolder = $_SERVER['DOCUMENT_ROOT'].'/storage/app/public';$linkedFolder = $_SERVER['DOCUMENT_ROOT'].'/public/storage'; symlink($targetFolder, $linkFolder); echo "done";   ## 2. Create a custom route to access storage Alright, this is kind of a hack but it works extremely fine. Just add the following route in your routes/web.php file:  Route::get('/storage/anyfolder/{filename}', function($filename){
$folder_path = storage_path('app/public/anyfolder/'.$filename);

// check if the file exists
if(!File::exists($folder_path)) { abort(404); }$file = File::get($folder_path);$type = File::mimeType($folder_path);$response = Response::make($file, 200);$response->header("Content-Type", $type); return$response;



Now, you can access your images or any other assets easily using:


]);



VIM

# Save a file

Published on May 25th, 2020

Want to save your work? Type :w

Type :wq! to save your file and quit VIM at the same time.

VIM

# Quit VIM

Published on May 25th, 2020

One of the most infamous issues that new users of VIM faces when using it for the first time. Press :q to quit VIM

If you've worked on a file and want to save and quit? Just type :wq!.

I hope that solved your quitting issue with VIM.

VIM

# Insert mode

Published on May 25th, 2020

I get it, a lot of people are confused on how to start typing on VIM. All you have to do is press the A key, the editor will be switched to insert mode.

Press ESC key to switch back to normal mode.

When zipping a directory or a bunch of files, there'll be a lot of stuff that you want to include and exclude.

To exclude a file:


zip -r files.zip . -x file_1 file_2



Alternatively, you can choose to include files:


zip -r files.zip . -i file_1 file_2



Terminal

# Find a file by extension

Published on May 25th, 2020

This comes in handy whenever I want to look for files that exists with a specific extension in a computer or server:


find . -name "*.ext"



In addition, sometimes, you might want to look for a bunch of files with a specific extension but with matching keywords:


find .name "*.ext" | grep "keyword"



## BONUS: Display list of files by extension with file sizes

Last month, I was trying to free up some space in our company server, so I realized that there were a lot of .zip files taking up a lot of space. So, I wrote a few commands to get me a list of zip files with their file sizes in sorting order into a .txt file:


find . -iname \*.zip -exec du -sh {} \; > zipfiles.txt
sort -rh zipfiles.txt > newfile.txt



You can .zip with any extension to suit your needs! :)

This helped me a lot whenever I'm in a remote server trying to find a keyword or specific text amongst a bunch of files.

This command will save you a lot of time:


grep -rwn [path] -e 'pattern'


• r stands for recursion
• n displays the line number
• w matches the whole word

Refer to man find pages for more info.

Before you integrate Excel into your application, make sure your project meets the following requirements:

• PHP v7.0 or greater
• Laravel v5.5 or greater

Download the maatwebsite/excel package using Composer:


composer require maatwebsite/excel



## Add it to service provider

By default, this will be done automatically when you're installing the package but if you want to do it yourself, add this in your config/app.php file:


<?php
...
'providers' => [
...
Maatwebsite\Excel\ExcelServiceProvider::class,
],

...
'aliases' => [
...
],
?>



Last but not the least, run the vendor:publish command using artisan to publish your configuration:


php artisan vendor:publish -provider="Maatwebsite\Excel\ExcelServiceProvider"



Upon publishing, the config/excel.php configuration file will be created where you can make your changes.

Hope this helps you out!

VIM

# Enable spellcheck

Published on May 25th, 2020

This can be useful when you're writing stuff, just do the following:


:set spellcheck=[lang]



VIM

# Clear all lines

Published on May 25th, 2020

1. Switch to normal mode by pressing ESC key
2. Press gg and it will take you to first line of the file.
3. Then type dG and it will clear all the lines from start to the end of the file.

Linux

# Check Ubuntu version

Published on May 25th, 2020

Want to know the current version of your Ubuntu distro? Type this:


lsb_release -r



Git

# Check branch status

Published on May 25th, 2020

Ever wondered if you've edited or committed anything in your project before pushing it to your repository, do this:


git status



Terminal

# Check RAM and disk space

Published on May 25th, 2020

## RAM space

Type the following command to view available memory in your system:


free -h



## Disk space

Type the following command to view available disk space in your system:


df -h



Wanted to view the size of a file in terminal but don't understand the number of bytes displayed? No worries, just type this command and it'll display the size of the in human-readable format:


du -sh filename.ext



Git

# Checkout branch

Published on May 25th, 2020

Want to create a new branch in your project? Simple, just do this:


git checkout -b new_branch



By doing this, you'll automatically be shifted to a new branch of your project. To check which branch you're working on, type this:


git branch



And you should be able to see your current branch marked with a *:


master
* new_branch