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
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
Are you new to using Git? Then this is for you.
Go to GitHub and create your account with your email address.
Just create a new project with whatever you wanted. For this, you can just create git-starter-repo
or something like that.
Now, go to your project directory and initialize git by doing the following:
git init
Add your files to the repository by doing the following:
git add .
Or if you want add selected files:
git add file_1 file_2
Before you push your changes, you need to write a message about what changes are done:
git commit -m "this is my first commit"
Do the following to link your project to the repo that you've created in step 1:
git remote add origin https://github.com/youraccount/repositoryname.git
You can decide which branch you wanted to push but initially, you'll have one branch, which is called master
:
git push -u origin master
Or if you have an existing branch, just replace master
with yourbranchname
.
Hope that helps you out!
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
I'm challenging myself to write a book on how to build simple applications using ReactJS
Over the past few months, I've been spending some of my free time to learn ReactJS and I've got to say, I really like it and got a hang of it after lots of trials and errors.
Just to make it clear, I didn't become a ReactJS expert or something but I figured that writing a book on something that you've learnt would help you understand the material much more deeper.
And since I do believe in it, I decided to challenge myself to write a book on it.
I aim to cover the fundamentals and concepts of ReactJS using a progressive and an example-driven approach. You know like on how to write reusable UI components, handle user events and interactions and managing state and props of a component.
By the end of this book, the reader will have solid understanding of React's concepts and be able to build cool applications using it.
Honestly, I didn't plan on the size of the book yet but the practical content for it i.e. the actual code and applications are ready. I aim to release it somewhere around late April 2020.
Umm, nope! I believe that knowledge should be accessible for everyone and I plan on making the book open source, so that it can get updated as per the latest changes.
I know it's a short article but I feel like I wanted to challenge myself with a small goal for this year.
Let's see how it goes!
Sharing my experiences of using events and listeners in my Laravel application.
Recently, I have started learning Laravel and now, I'm building an application for my new company using this amazing framework.
My senior developer was curious and thought of having a conversation with me that went like this:
Senior dev: Hmm, can I have a look at your code?
Me: Oh sure, here take a look.
Senior: (Goes through project file structure)
Senior: So, have you ever thought of using events in your application?
Me: Yeah, I wrote a custom JavaScript file to handle and fire events on the client-side like validating the forms and passing async requests to the server.
Senior: Hmm, that's okay but I'm talking using events in Laravel.
At this point, I was pretty clueless and I didn't know what the heck was going on. Events in PHP? I mean, I know about it in JavaScript because of it's event-driven architecture that we are all familiar with. But in PHP? I didn't know that.
Still confused, he proceeds to explain about it's concepts in an abstract manner and thanks to him, it induced my curiosity by asking myself: What's the deal in between using events over function calls using a route on a standard controller?
In today's article, I'll be talking about why and when to use events over function calls using Laravel in your application.
An event is a piece of reusable logic stored somewhere in your application that has a set of listeners waiting to be executed, if triggered.
Let's say, you have a simple CRUD application that involves user registration. Whenever a user registers, you may want to perform certain actions, such as:
You can add more but this is just to give you an idea. Let's see take a look at two different approaches:
If you're using an MVC framework (Laravel, in our case), you'd do this in a controller with a bunch of methods like so:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\User;
class UserController extends Controller {
public function index() {
// insert code to view users page
}
public function create(Request $request) {
$arr = [
'username' => $request->username,
'email' => $request->email,
'password' => bcrypt('something')
];
$user = User::create($arr);
$this->sendConfirmationEmail($user);
$this->subscribeToMailingList($user);
}
// Send confirmation email to user
private function sendConfirmationEmail($user) {
// insert code
}
// Subscribe user to mailing list
private function subscribeToMailingList($user) {
// insert code
}
}
?>
This is approach is self-contained and simple to follow but you're also adding in a lot of responsibility to your controller.
Not only that, what if the user wants to register from another place in your application, in that case, you'll have to duplicate your logic in multiple places.
Using this approach, you can split this into Event and Listener files in your application.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\User;
class UserController extends Controller {
public function index() {
// insert code to view users page
}
public function create(Request $request) {
$arr = [
'username' => $request->username,
'email' => $request->email,
'password' => bcrypt('something')
];
$user = User::create($arr);
// Emit event
event(new UserRegistered($user));
}
}
?>
This is how your UserRegistered event would look like:
<?php
namespace App\Events;
use Illuminate\Queue\SerializeModels;
use App\User;
class UserRegistered {
use SerializesModels;
public $user;
public function __construct(User $user) {
$this->user = $user;
}
}
?>
And this is how your SendConfirmationEmail listener would look like:
<?php
namespace App\Listeners;
use App\Events\UserRegistered;
class SendConfirmationEmail {
public function __construct(User $user) {
// insert code
}
public function handle(UserRegister $event) {
// insert code
}
}
?>
Using this approach, you can use the UserRegistered event anywhere you wanted in your application. No matter what happens, it will trigger the same actions as it was intended to do so. If you want to add a new functionality, create a new listener and register it with the event in your EventServiceProvider file like this:
<?php
protected $listen = [
'App\Events\UserRegistered' => [
'App\Listeners\SendConfirmationEmail',
],
];
?>
If you follow this approach, your logic complexity is toned down and the controller will have less responsibility.
Just like this answer that I found on StackOverflow question regarding events and listeners over calling functions:
You might not be in control of the code that's doing the calling. Or even if you are, you don't want to introduce dependencies into that code.
Think about it, what if you built an API or library that you want people to use but don't want them to modify the source code. Instead, you could provide a documentation that states specific events are raised under specific circumstances, in turn, they can write code that responds to such events.
I'm sure that there are more examples as to where this methodology might be applied.
Truth be told, it depends. If you have a simple application, then a functional approach is all you need but it's a larger and more complicated application, using Events and Listeners can be a better option.
Please note, I'm not an expert at this topic as I'm still learning and I thought of sharing what I had learnt. If you have any suggestions or thoughts, please share it with me on Twitter or send me a message to my inbox.
Hope you liked reading this article.
Stay tuned for more.
Implemented a mathematically beautiful generative pattern that looks deceivingly complex to the human.
Beautiful, isn't it? It might look complex but it's mathematically quite impressive. Making this pattern wasn't hard but it definitely took a lot of trial and error to get it right and honestly, I don't really know if it's this is the most efficient way to generate this pattern.
This article isn't a tutorial but rather, I'll be talking about the algorithm itself. However, you can check out the source code in my GitHub repository.
In order to achieve that "stacked" effect, there are two things to keep in mind:
The logic is quite similar to the Overlapping Rectangles problem except this is done with circles.
This method will help generate valid circles with a random radius. Circles that don't overlap or collide with other circles are considered to be valid.
// Generate a valid circle
const generateCircle = () => {
let newCircle;
let isValidCircle = false;
for(let i=0; i<attempts; i++) {
newCircle = {
x: Math.floor(Math.random() * width),
y: Math.floor(Math.random() * width),
radius: minRadius
};
if(checkForCollision(newCircle)) {
continue;
}
else {
isValidCircle = true;
break;
}
}
if(!isValidCircle) { return; }
for(let i=minRadius; i<=maxRadius; i++) {
newCircle.radius = i;
if(checkForCollision(newCircle)) {
newCircle.radius--;
break;
}
}
circles.push(newCircle);
drawCircleOnCanvas(context, newCircle, colors[Math.floor(Math.random() * colors.length)]);
}
Thanks to some online research, I was able implement the Euclidean Distance equation that helped with calculating the distances between each circle and detect for collisions. Along with that, I also found another article on Touching Circles that was quite useful.
These are the formulas used to detect the collision:
Find the distance between two centres \[ AB = \sqrt{ (x2 - x1)^2 - (y2 - y1)^2} \]
Calculate the radii of both circles. \[R = r1 + r2\]
If the radii is greater than or equal to the euclidean distance of both circles, then it's a valid circle with no collisions.
// Check for collision in a canvas
const checkForCollision = (newCircle) => {
let x2 = newCircle.x;
let y2 = newCircle.y;
let r2 = newCircle.radius;
// Determine the euclidean distance between two circle
// using Pythagorean Theorem.
// Refer to:
// https://en.wikipedia.org/wiki/Euclidean_distance
for(let i=0; i<circles.length; i++) {
let otherCircle = circles[i];
let r1 = otherCircle.radius;
let x1 = otherCircle.x;
let y1 = otherCircle.y;
let xx = ((x2 - x1) * (x2 - x1));
let yy = ((y2 - y1) * (y2 - y1));
let radii = r2 + r1;
let euclidDistance = Math.sqrt(xx + yy);
if(radii >= euclidDistance) {
return true;
}
}
// Check collision on top
if(x2 + r2 >= width ||
x2 - r2 <= 0) {
return true;
}
// Check collision on bottom
if(y2 + r2 >= width ||
y2 - r2 <= 0) {
return true;
}
//else return false
return false;
}
I'm thinking of implementing more generative patterns like Triangular Mesh and Piet Mondrian's Red, Blue and Yellow composition.
Hope you liked reading this article.
Stay tuned for more!
Learn how to deploy your Laravel application along with a database on Heroku.
In my previous article, I talked about how to setup your environment for developing your Laravel applications. Today, I'll be talking about deploying your application along with a database on Heroku.
I wrote a simple CRUD application using Laravel but didn't understand on how to host it. I tried to host it on free shared hosting service but apparently, most of them don't support PHP system calls like proc_open(). However, if it was a VPS hosting service, it's supported but ain't nobody got time for shelling out cash for a test drive.
As an alternative, I went on google and discovered that Heroku does support my requirements and it worked flawlessly, which is why I thought of sharing this information to others as well.
If you're a developer who's at the early stages of learning Laravel (like me 😆), then this article is for you.
You'll be doing some minor configurations, so you should be fine as long as you have a stable internet connection, familiar with using the CLI (Command Line Interface) and have some PHP knowledge.
If you're a Windows user, please Git for Windows. Else, if you're a Linux or macOS user, you should be fine.
You can ignore the first two steps if you already know about Heroku and how to work with it but please follow the rest of the steps:
You can install this directly from the command line by typing the following:
sudo snap install heroku --classic
If you don't have a Heroku account yet, create an account now and once you're done with that, type the following:
heroku login
Follow the login instructions from the command line prompt, fill in your login credentials and you'll be in!
Once, you're done with that, create a repository by doing the following:
heroku create
In a few seconds, you'll get a randomly generated domain address, which is the link to your Heroku repository. If you can't remember the link, it's fine, you can make changes to it in your Heroku account.
In case, you don't know what's a Procfile, it's a file that specifies the commands that needs to be executed by the application on startup. You can declare a variety of process types, click here to learn more.
Since our application is PHP based, we need to add some specific command that selects the server on boot, I chose Apache server for this project:
cd your_laravel_project
touch Procfile
echo "web: vendor/bin/heroku-php-apache2 web/" > Procfile
It's similar to pushing your code into your GitHub, except this time, it's your Heroku repository. Type the following in your command line:
git add .
git commit -m "pushing application to repo"
git push heroku master
To check if your application is launched, type the following:
heroku open
At this stage, you might face Error 500, that's normal because we'll take care of that in the next step.
We need to add some config variables that changes the way your app behaves. So, let's start adding it:
heroku config:set APP_DEBUG=true
heroku config:set APP_KEY=yourlaravelapplicationkey
heroku config:set APP_URL=https://yourwebsite.herokuapp.com
heroku config:set REDIRECT_HTTPS=true
In this configuration, you have done the following: - Enabled debug mode - Set your Laravel application's base64 encrypted key - The website's URL - Force HTTPS redirect (Useful, when you're calling external assets that uses HTTPS protocol)
Note: You can find your APP_KEY in your .env file that's found in your project directory.
Initially, I built the database on MySQL but I later learnt that Heroku gives a free PostgreSQL starter database. I've never tried PostgreSQL before but it's quite similar to MySQL, so you shouldn't worry about your schema as Laravel supports PostgreSQL and MySQL databases by default.
Type the following in the command line:
heroku addons:create heroku-postgresql:hobby-dev
This will create a PostgreSQL database and sets a DATABASE_URL, which contains the username and password to the database. To check it, type the following:
heroku config
Now, go to your project directory and open the config/database.php file and add the following:
<?php
// Place these variables above
$url = parse_url(getenv("DATABASE_URL"));
$host = $url["host"]??null;
$username = $url["user"]??null;
$password = $url["pass"]??null;
$database = substr($url["path"], 1)??null;
// Replace the default connection
'default' => env('DB_CONNECTION', 'pgsql_prod'),
// Under the connections attribute, create a new connection called 'pgsql_prod'
'pgsql_production' => [
'driver' => 'pgsql',
'host' => $host,
'database' => $database,
'username' => $username,
'password' => $password,
'charset' => 'utf-8',
'prefix' => '',
'schema' => 'public',
],
?>
Push the new changes to your repository:
git add .
git commit -m "configured database"
git push heroku master
One last step, we need to create the tables from your schema, so type the following:
heroku run php /app/artisan migrate --seed
Follow the command line prompt and voila, you have successfully deployed your Laravel application with a database on Heroku.
Well, I hope you found this article really useful especially if you're a beginner. If you do find this useful, please share it with others too!
Stay tuned for more!
Wanted to install Laravel but scared of configuring files on your host operating system? This article is for you.
I started learning Laravel and I thought of writing a small tutorial on how to setup your own local development environment for Laravel projects with Laravel Homestead and Vagrant.
It's an official package from Laravel that provides a neat development environment that comes along with a Vagrant box that has pre-installed software. Read their documentation to know more about it.
Note: The examples of this tutorial are applicable to any developer that uses any UNIX-based operating systems such as macOS or any Linux distributions like Ubuntu. If you're using Windows, I recommend that you install Git for Windows on your local machine.
The only requirement for this tutorial is that you should be familiar with using the command-line interface.
VirtualBox is the software used to run a virtual machine with a sandbox operating system within your own computer.
Vagrant is a software that's used to manage a development environment. Through the command-line, you can perform any operation such as installing an OS, configuration, deployment and so on.
You can install VirtualBox and Vagrant via the command-line:
sudo apt install virtualbox vagrant
Once you're done installing them, you should add the laravel/homestead box to your Vagrant installation using the following command:
vagrant box add laravel/homestead
To check if it has been installed, use the following command:
vagrant box list | grep "homestead"
Using VirtualBox and Vagrant allows you to simulate your Laravel development environment without messing up any configurations on your hosting system. Even if you did, no worries, Vagrant boxes are disposable, so you can destroy and create a new box again in minutes.
You can install Homestead by cloning it's repository onto your local machine by typing the following command:
git clone https://github.com/laravel/homestead.git ~/projects/Homestead
Once you're done cloning the repository, go inside the projects/Homestead directory and run the init.sh or init.bat (for Windows) to create the Homestead.yaml configuration file:
cd projects/Homestead
bash init.sh
Open the default Homestead.yaml file and make the following changes:
---
ip: "192.168.10.10"
memory: 2048
cpus: 2
provider: virtualbox
authorize: ~/.ssh/id_rsa.pub
keys:
- ~/.ssh/id_rsa
folders:
- map: ~/projects/code
to: /home/vagrant/projects/code
sites:
- map: homestead.test
to: /home/vagrant/projects/code/public
databases:
- homestead
The documentation for Laravel Homestead doesn't really talk about generating SSH keys used to access the Vagrant box. Use the following command to generate it using ssh-keygen on the command-line:
ssh-keygen -t rsa -C "root@homestead"
Make sure that you have created a folder named code in your projects directory. This folder will keep all of your Laravel project files in sync between your local machine and Homestead environment.
Time to install Laravel into your virtual machine. So, get switch on your virtual machine by doing the following in the command-line:
vagrant up
As you're switching it on for the first time, depending on your internet connection, it might take somewhere around 10-20 minutes to getting it running but it'll be fine afterwards.
Alright, login to your Vagrant machine by doing the following the command-line:
vagrant ssh
Once you're in, go to your code directory and type the following in the command-line:
composer global require laravel/installer
Now, it's time to create a new Laravel project by simply typing the following command:
laravel new projectname
It'll take some time to generate the necessary files and boilerplate code and after that, you're good to go!
Oh, you should be able to see the Laravel project files in your local machine as it's synced with the virtual machine and local machine. That means, any changes made on either machines will be synced and reflected on both ends.
One last step, make sure you map your project's test domain onto your local machine's hosts file.
Open a text-editor of your choice and do the following in the etc/hosts file:
127.0.0.1 localhost
::1 localhost
# Add this line (Note: It can be any URL)
127.0.0.1 homestead.test
Now, go to your browser and type homestead.test and you should be able to see your Laravel project's sample layout.
As mentioned, in the beginning of this article, I have started to learn Laravel and I'll be building some projects and writing out my experiences about it soon.
I hope you liked reading this article and please share it with others if you do find this tutorial useful.
Stay tuned for more!